-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-resize.go
354 lines (333 loc) · 9.22 KB
/
image-resize.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Command image-resize resizes (re-scales) images of different formats
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/artyom/autoflags"
"github.com/bamiaux/rez"
"github.com/disintegration/gift"
"github.com/rwcarlsen/goexif/exif"
"github.com/soniakeys/quant/mean"
"golang.org/x/image/bmp"
"golang.org/x/image/draw"
"golang.org/x/image/tiff"
)
func main() {
p := params{
JpegQuality: jpeg.DefaultQuality,
}
autoflags.Define(&p)
flag.Parse()
if err := do(p); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
type params struct {
Width int `flag:"width,width to enforce"`
Height int `flag:"height,height to enforce"`
MaxWidth int `flag:"maxwidth,max. allowed width"`
MaxHeight int `flag:"maxheight,max. allowed height"`
Input string `flag:"input,input file"`
Output string `flag:"output,output file"`
Square bool `flag:"square,crop image to square by smaller side before processing"`
NoFill bool `flag:"nofill,do not draw transparent inputs over white for non-png outputs"`
JpegQuality int `flag:"q,jpeg quality (1-100)"`
}
func do(par params) error {
if par.JpegQuality < 1 || par.JpegQuality > 100 {
par.JpegQuality = jpeg.DefaultQuality
}
tr, err := newTransform(par.Width, par.Height, par.MaxWidth, par.MaxHeight)
if err != nil {
return err
}
f, err := os.Open(par.Input)
if err != nil {
return err
}
defer f.Close()
headBuf := new(bytes.Buffer)
teeReader := io.TeeReader(f, headBuf)
cfg, kind, err := image.DecodeConfig(teeReader)
if err != nil {
return err
}
if cfg.Width*cfg.Height > pixelLimit {
return fmt.Errorf("image dimensions %d×%d exceeds limit", cfg.Width, cfg.Height)
}
width, height, err := tr.newDimensions(cfg.Width, cfg.Height)
if err != nil {
return err
}
imageDataReader := io.LimitReader(io.MultiReader(headBuf, f), maxFileSize)
exifChan := make(chan exifData, 1)
if kind == "jpeg" {
prd, pwr := io.Pipe()
defer pwr.Close()
imageDataReader = io.TeeReader(imageDataReader, pwr)
go func() {
defer func() {
if p := recover(); p != nil {
fmt.Fprintln(os.Stderr, "exif decode failed")
}
io.Copy(ioutil.Discard, prd)
}()
data, err := exif.Decode(prd)
exifChan <- exifData{data, err}
}()
}
img, _, err := image.Decode(imageDataReader)
if err != nil {
return err
}
var rotatefunc func(image.Image) image.Image
var swapWH bool
if kind == "jpeg" {
select {
case ed := <-exifChan:
rotatefunc, swapWH = useExifOrientation(ed)
default:
fmt.Fprintln(os.Stderr, "exif decode failed/stuck")
}
}
if swapWH {
par.Width, par.Height = par.Height, par.Width
par.MaxWidth, par.MaxHeight = par.MaxHeight, par.MaxWidth
tr, err = newTransform(par.Width, par.Height, par.MaxWidth, par.MaxHeight)
if err != nil {
return err
}
width, height, err = tr.newDimensions(cfg.Width, cfg.Height)
if err != nil {
return err
}
}
if par.Square {
type subImager interface {
SubImage(r image.Rectangle) image.Image
}
si, ok := img.(subImager)
if !ok {
return errors.New("cannot crop image")
}
minSide := cfg.Width
if cfg.Height < minSide {
minSide = cfg.Height
}
x0, y0 := (cfg.Width-minSide)/2, (cfg.Height-minSide)/2
img = si.SubImage(image.Rect(x0, y0, x0+minSide, y0+minSide))
width, height, err = tr.newDimensions(minSide, minSide)
if err != nil {
return err
}
}
outSuffix := strings.ToLower(filepath.Ext(par.Output))
var outImg image.Image
if (cfg.Width <= width && cfg.Height <= height) && (tr.MaxWidth > 0 || tr.MaxHeight > 0) {
// noupscale case
outImg = img
goto saveOutput
}
switch img.(type) {
case *image.YCbCr, *image.RGBA, *image.NRGBA, *image.Gray:
outImg, err = resize(img, width, height, rez.NewLanczosFilter(3))
default:
outImg, err = resizeFallback(img, width, height)
}
if err != nil {
return err
}
saveOutput:
if op, ok := outImg.(opaquer); ok && !par.NoFill && !op.Opaque() && outSuffix != ".png" {
newOut := image.NewRGBA(outImg.Bounds())
draw.Copy(newOut, image.Point{}, image.White, newOut.Bounds(), draw.Src, nil)
draw.Copy(newOut, image.Point{}, outImg, newOut.Bounds(), draw.Over, nil)
outImg = newOut
}
if rotatefunc != nil {
outImg = rotatefunc(outImg)
}
of, err := os.Create(par.Output)
if err != nil {
return err
}
defer of.Close()
switch outSuffix {
case ".gif":
gifOpts := &gif.Options{NumColors: 256, Quantizer: mean.Quantizer(256)}
if pImg, ok := img.(*image.Paletted); ok {
gifOpts.NumColors = len(pImg.Palette)
gifOpts.Quantizer = mean.Quantizer(gifOpts.NumColors)
}
err = gif.Encode(of, outImg, gifOpts)
case ".png":
enc := png.Encoder{CompressionLevel: png.BestCompression}
err = enc.Encode(of, outImg)
case ".tiff", ".tif":
err = tiff.Encode(of, outImg,
&tiff.Options{Compression: tiff.Deflate, Predictor: true})
case ".bmp":
err = bmp.Encode(of, outImg)
default:
err = jpeg.Encode(of, outImg, &jpeg.Options{Quality: par.JpegQuality})
}
if err != nil {
return err
}
return of.Close()
}
type transform struct {
Width int
Height int
MaxWidth int
MaxHeight int
}
func (tr transform) newDimensions(origWidth, origHeight int) (width, height int, err error) {
if origWidth == 0 || origHeight == 0 {
return 0, 0, errors.New("invalid source dimensions")
}
var w, h int
switch {
case tr.MaxWidth > 0 || tr.MaxHeight > 0:
w, h = tr.MaxWidth, tr.MaxHeight
// if only one max dimension specified, calculate another using
// original aspect ratio
if w == 0 {
w = origWidth * h / origHeight
}
if h == 0 {
h = origHeight * w / origWidth
}
if origWidth <= w && origHeight <= h {
return origWidth, origHeight, nil // image already fit
}
if tr.MaxWidth > 0 && tr.MaxHeight > 0 {
// maxwidth and maxheight form free aspect ratio, need
// to adjust w and h to match origin aspect ratio, while
// keeping dimensions inside max bounds
if float64(origWidth)/float64(origHeight) > float64(w)/float64(h) {
h = origHeight * w / origWidth
} else {
w = origWidth * h / origHeight
}
}
case tr.Width > 0 || tr.Height > 0:
// if both width and height specified, free aspect ratio is
// applied; if only one is set, original aspect ratio is kept
w, h = tr.Width, tr.Height
if w == 0 {
w = origWidth * h / origHeight
}
if h == 0 {
h = origHeight * w / origWidth
}
default:
return 0, 0, fmt.Errorf("invalid transform %v", tr)
}
if w*h > pixelLimit || w >= 1<<16 || h >= 1<<16 {
return 0, 0, errors.New("destination size exceeds limit")
}
return w, h, nil
}
func newTransform(width, height, maxWidth, maxHeight int) (transform, error) {
tr := transform{
Width: width,
Height: height,
MaxWidth: maxWidth,
MaxHeight: maxHeight,
}
if tr.Width == 0 && tr.Height == 0 && tr.MaxWidth == 0 && tr.MaxHeight == 0 {
return transform{}, errors.New("no valid dimensions specified")
}
if tr.Width*tr.Height > pixelLimit || tr.MaxWidth > pixelLimit || tr.MaxHeight > pixelLimit {
return transform{}, errors.New("destination size exceeds limit")
}
return tr, nil
}
func resize(inImg image.Image, width, height int, algo rez.Filter) (image.Image, error) {
var outImg image.Image
rect := image.Rect(0, 0, width, height)
switch inImg.(type) {
case *image.Gray:
outImg = image.NewGray(rect)
case *image.RGBA:
outImg = image.NewRGBA(rect)
case *image.NRGBA:
outImg = image.NewNRGBA(rect)
default:
outImg = image.NewYCbCr(rect, image.YCbCrSubsampleRatio420)
}
if err := rez.Convert(outImg, inImg, algo); err != nil {
return nil, err
}
return outImg, nil
}
func resizeFallback(inImg image.Image, width, height int) (image.Image, error) {
outImg := image.NewRGBA(image.Rect(0, 0, width, height))
draw.CatmullRom.Scale(outImg, outImg.Bounds(), inImg, inImg.Bounds(), draw.Src, nil)
return outImg, nil
}
const (
pixelLimit = 50 * 1000000
maxFileSize = 50 << 20
)
type opaquer interface {
Opaque() bool
}
type exifData struct {
exif *exif.Exif
err error
}
func useExifOrientation(ed exifData) (rotatefunc func(image.Image) image.Image, swapWH bool) {
if ed.err != nil || ed.exif == nil {
return
}
o, err := ed.exif.Get(exif.Orientation)
if err != nil || o == nil || len(o.Val) != 2 {
return
}
for _, x := range o.Val {
switch x {
case 3: // 180º
return rotate180, false
case 6: // 90ºCCW
return rotate90ccw, true
case 8: // 90ºCW
return rotate90cw, true
case 4: // vertical flip
return flipVertical, true
case 2: // horizontal flip
return flipHorizontal, true
}
}
return
}
func flipHorizontal(src image.Image) image.Image { return rotate(src, gift.FlipHorizontal()) }
func flipVertical(src image.Image) image.Image { return rotate(src, gift.FlipVertical()) }
func rotate90ccw(src image.Image) image.Image { return rotate(src, gift.Rotate270()) }
func rotate90cw(src image.Image) image.Image { return rotate(src, gift.Rotate90()) }
func rotate180(src image.Image) image.Image { return rotate(src, gift.Rotate180()) }
func rotate(src image.Image, filter gift.Filter) image.Image {
g := gift.New(filter)
var dst draw.Image
switch src.(type) {
case *image.Gray:
dst = image.NewGray(g.Bounds(src.Bounds()))
default:
dst = image.NewRGBA(g.Bounds(src.Bounds()))
}
g.Draw(dst, src)
return dst
}