1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
package converter
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"log/slog"
"strings"
"golang.org/x/image/draw"
"github.com/SayaAndy/saya-today-thumbnail-generator/config"
"github.com/kolesa-team/go-webp/encoder"
"github.com/kolesa-team/go-webp/webp"
)
var _ Converter = (*WebpConverter)(nil)
type WebpConverter struct {
maxWidth int
maxHeight int
quality int
}
func NewWebpConverter(cfg *config.ConverterConfig) (Converter, error) {
if cfg.Type != "webp" {
return nil, fmt.Errorf("invalid storage type for WebpConverter")
}
webpCfg := cfg.Config.(*config.WebpConfig)
return &WebpConverter{webpCfg.Size.MaxWidth, webpCfg.Size.MaxHeight, webpCfg.Quality}, nil
}
func (p *WebpConverter) DeductOutputPath(inputPath string) string {
pathParts := strings.Split(inputPath, ".")
if len(pathParts) < 2 {
return inputPath + ".webp"
}
pathParts[len(pathParts)-1] = "webp"
return strings.Join(pathParts, ".")
}
func (p *WebpConverter) Process(contentType string, reader io.ReadCloser, writer io.WriteCloser) error {
var src image.Image
var err error
defer reader.Close()
defer writer.Close()
switch contentType {
case "image/jpeg":
src, err = jpeg.Decode(reader)
if err != nil {
return fmt.Errorf("decode jpeg: %w", err)
}
case "image/png":
src, err = png.Decode(reader)
if err != nil {
return fmt.Errorf("decode png: %w", err)
}
default:
return fmt.Errorf("unsupported content type: %s", contentType)
}
opts, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, float32(p.quality))
if err != nil {
return fmt.Errorf("create webp encoder options: %w", err)
}
xCoef := float64(p.maxWidth) / float64(src.Bounds().Max.X)
if p.maxWidth == 0 {
xCoef = 1
}
yCoef := float64(p.maxHeight) / float64(src.Bounds().Max.Y)
if p.maxHeight == 0 {
yCoef = 1
}
slog.Debug("calculated coefficients", slog.Float64("x_coef", xCoef), slog.Float64("y_coef", yCoef))
if xCoef > 1 && yCoef > 1 {
return webp.Encode(writer, src, opts)
}
minCoef := xCoef
if yCoef < minCoef {
minCoef = yCoef
}
dst := image.NewRGBA(image.Rect(0, 0, int(float64(src.Bounds().Max.X)*minCoef+0.5), int(float64(src.Bounds().Max.Y)*minCoef+0.5)))
draw.CatmullRom.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
return webp.Encode(writer, dst, opts)
}
|