2020-10-09 11:09:17 +00:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
2020-10-22 15:27:58 +00:00
|
|
|
"bytes"
|
2020-11-18 12:41:36 +00:00
|
|
|
"encoding/base64"
|
2020-10-22 15:27:58 +00:00
|
|
|
"fmt"
|
2020-10-09 11:09:17 +00:00
|
|
|
"image"
|
|
|
|
"image/jpeg"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2020-10-22 15:27:58 +00:00
|
|
|
type EncodeConfig struct {
|
2020-10-27 14:42:42 +00:00
|
|
|
Quality int
|
2020-10-22 15:27:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Encode(w io.Writer, img image.Image, config EncodeConfig) error {
|
2020-10-09 11:09:17 +00:00
|
|
|
// Currently a wrapper for renderJpeg, but this function is useful if multiple render formats are needed
|
2020-10-22 15:27:58 +00:00
|
|
|
return renderJpeg(w, img, config)
|
2020-10-09 11:09:17 +00:00
|
|
|
}
|
|
|
|
|
2020-10-22 15:27:58 +00:00
|
|
|
func renderJpeg(w io.Writer, m image.Image, config EncodeConfig) error {
|
2020-10-09 11:09:17 +00:00
|
|
|
o := new(jpeg.Options)
|
2020-10-22 15:27:58 +00:00
|
|
|
o.Quality = config.Quality
|
2020-10-09 11:09:17 +00:00
|
|
|
|
|
|
|
return jpeg.Encode(w, m, o)
|
|
|
|
}
|
2020-10-22 15:27:58 +00:00
|
|
|
|
2020-10-22 15:59:01 +00:00
|
|
|
func EncodeToBestSize(bb *bytes.Buffer, img image.Image, size ResizeDimension) error {
|
2020-10-22 15:27:58 +00:00
|
|
|
q := MaxJpegQuality
|
|
|
|
for q > MinJpegQuality-1 {
|
|
|
|
|
|
|
|
err := Encode(bb, img, EncodeConfig{Quality: q})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if DimensionSizeLimit[size].Ideal > bb.Len() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if q == MinJpegQuality {
|
2020-10-27 14:42:42 +00:00
|
|
|
if DimensionSizeLimit[size].Max > bb.Len() {
|
2020-10-22 15:27:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
2020-11-24 23:16:19 +00:00
|
|
|
return fmt.Errorf(
|
|
|
|
"image size after processing exceeds max, expect < '%d', received < '%d'",
|
|
|
|
DimensionSizeLimit[size].Max,
|
|
|
|
bb.Len(),
|
|
|
|
)
|
2020-10-22 15:27:58 +00:00
|
|
|
}
|
|
|
|
|
2020-10-22 15:59:01 +00:00
|
|
|
bb.Reset()
|
2020-10-22 15:27:58 +00:00
|
|
|
q -= 2
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2020-11-18 12:41:36 +00:00
|
|
|
|
|
|
|
func GetPayloadDataURI(payload []byte) (string, error) {
|
2020-11-24 13:13:46 +00:00
|
|
|
if len(payload) == 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
2020-11-18 12:41:36 +00:00
|
|
|
mt, err := GetMimeType(payload)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
b64 := base64.StdEncoding.EncodeToString(payload)
|
|
|
|
|
|
|
|
return "data:image/" + mt + ";base64," + b64, nil
|
|
|
|
}
|