-
Notifications
You must be signed in to change notification settings - Fork 1
/
resizer.go
231 lines (196 loc) · 5.57 KB
/
resizer.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package imageresizer
import (
"errors"
"fmt"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"math"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
type Template struct {
width float64
height float64
ratio float64
crop bool
upscale bool
}
var convertCmd = GetEnv("CMD_CONVERT", "convert")
var optimizerCmd = map[string]string{
"png": GetEnv("CMD_OPTIMIZER_PNG", "pngquant --force --ext .png --skip-if-larger --quality 0-75 --speed 4 --strip --") + " %file",
"jpg": GetEnv("CMD_OPTIMIZER_JPG", "jpegoptim --force --strip-all --max 75 --quiet --all-progressive") + " %file",
"gif": GetEnv("CMD_OPTIMIZER_GIF", "gifsicle --batch --optimize=3") + " %file",
"svg": GetEnv("CMD_OPTIMIZER_SVG", "svgcleaner") + " %file %file",
"webp": GetEnv("CMD_OPTIMIZER_WEBP", "cwebp -m 6 -pass 10 -mt -q 75 -quiet") + " %file -o %file",
}
var optimizerCmdExtMapper = map[string]string{
".png": "png",
".jpg": "jpg",
".jpeg": "jpg",
".gif": "gif",
".webp": "webp",
}
var supportedFormats = [...]string{
".webp",
".png",
".svg",
".jpg",
".gif",
".jpeg",
".bmp",
".tiff",
".pdf",
}
func NewTemplate(template string) *Template {
width := 0.0
height := 0.0
ratio := 0.0
crop := false
upscale := false
parts := strings.Split(template, "-")
for _, part := range parts {
if part == "" {
continue
} else if part[0] == 'w' {
width, _ = strconv.ParseFloat(part[1:], 64)
} else if part[0] == 'h' {
height, _ = strconv.ParseFloat(part[1:], 64)
} else if strings.Contains(part, "x") {
sides := strings.SplitN(part, "x", 2)
ratioWidth, _ := strconv.ParseFloat(sides[0], 64)
ratioHeight, _ := strconv.ParseFloat(sides[1], 64)
if ratioHeight > 0 {
ratio = ratioWidth / ratioHeight
}
} else if part == "crop" {
crop = true
} else if part == "upscale" {
upscale = true
}
}
return &Template{width, height, ratio, crop, upscale}
}
func (t *Template) getDimensions(originalWidth float64, originalHeight float64) (int, int) {
outputWidth := originalWidth
outputHeight := originalHeight
originalRatio := originalWidth / originalHeight
if t.width > 0 && t.height > 0 {
outputWidth = t.width
outputHeight = t.height
} else if t.width > 0 && t.ratio > 0 {
outputWidth = t.width
outputHeight = t.width / t.ratio
} else if t.height > 0 && t.ratio > 0 {
outputWidth = t.height * t.ratio
outputHeight = t.height
} else if t.ratio > 0 {
if originalRatio < t.ratio {
outputWidth = originalHeight * t.ratio
outputHeight = originalHeight
} else {
outputWidth = originalWidth
outputHeight = originalWidth / t.ratio
}
} else if t.width > 0 {
outputWidth = t.width
outputHeight = t.width / originalRatio
} else if t.height > 0 {
outputWidth = t.height * originalRatio
outputHeight = t.height
}
if t.crop && !t.upscale {
upscaleWidth := originalWidth / outputWidth
upscaleHeight := originalHeight / outputHeight
outputRatio := outputWidth / outputHeight
if upscaleWidth < 1 && upscaleWidth <= upscaleHeight {
outputWidth = originalWidth
outputHeight = originalWidth / outputRatio
} else if upscaleHeight < 1 && upscaleHeight < upscaleWidth {
outputWidth = originalHeight * outputRatio
outputHeight = originalHeight
}
}
return int(math.Round(outputWidth)), int(math.Round(outputHeight))
}
func GetImageDimensions(p string) (w int, h int, err error) {
f, err := os.Open(p)
if err != nil {
return
}
c, _, err := image.DecodeConfig(f)
if err != nil {
return
}
return c.Width, c.Height, nil
}
func ConvertFile(inputFilePath string, inputWidth int, inputHeight int, outputFilePath string, template *Template) (err error) {
outputWidth, outputHeight := template.getDimensions(float64(inputWidth), float64(inputHeight))
outputExt := strings.ToLower(filepath.Ext(outputFilePath))
var resizeGeometryArg, backgroundArg string
if template.crop {
resizeGeometryArg = "%dx%d^"
} else if template.upscale {
resizeGeometryArg = "%dx%d"
} else {
resizeGeometryArg = "%dx%d>"
}
if outputExt == ".jpg" || outputExt == ".jpeg" {
backgroundArg = "white"
} else {
backgroundArg = "none"
}
args := []string{
inputFilePath,
"-resize", fmt.Sprintf(resizeGeometryArg, outputWidth, outputHeight),
"-background", backgroundArg,
"-gravity", "center",
"-extent", fmt.Sprintf("%dx%d", outputWidth, outputHeight),
outputFilePath,
}
_ = os.MkdirAll(filepath.Dir(outputFilePath), 0777)
logger("RESIZE %s %v\n", convertCmd, args)
err = exec.Command(convertCmd, args...).Run()
return
}
func OptimizeFile(filePath string) (err error) {
ext := strings.ToLower(filepath.Ext(filePath))
optimizer, found := optimizerCmd[optimizerCmdExtMapper[ext]]
if !found || optimizer == "" {
return nil
}
args := strings.Split(strings.ReplaceAll(optimizer, "%file", filePath), " ")
logger("OPTIMIZE %v\n", args)
err = exec.Command(args[0], args[1:]...).Run()
return
}
func ValidateFilename(filePath string) error {
ext := strings.ToLower(filepath.Ext(filePath))
for _, f := range supportedFormats {
if f == ext {
return nil
}
}
return HttpError{errors.New("not supported file format"), http.StatusBadRequest}
}
func ValidateTemplate(template string) error {
if template != "original" && !strings.HasPrefix(template, "custom") {
return HttpError{errors.New("not supported template"), http.StatusBadRequest}
}
return nil
}
func ShouldNotResize(template string, filePath string) bool {
if template == "original" {
return true
}
ext := strings.ToLower(filepath.Ext(filePath))
return ext == ".svg" || ext == ".pdf"
}