diff --git a/transform.go b/transform.go index bba0176..b37d0ca 100644 --- a/transform.go +++ b/transform.go @@ -79,7 +79,9 @@ func Transform(img []byte, opt Options) ([]byte, error) { return buf.Bytes(), nil } -func resizeParams(m image.Image, opt *Options) (w, h int, resize bool) { +// resizeParams determines if the image needs to be resized, and if so, the +// dimensions to resize to. +func resizeParams(m image.Image, opt Options) (w, h int, resize bool) { // convert percentage width and height values to absolute values imgW := m.Bounds().Max.X - m.Bounds().Min.X imgH := m.Bounds().Max.Y - m.Bounds().Min.Y @@ -98,7 +100,7 @@ func resizeParams(m image.Image, opt *Options) (w, h int, resize bool) { h = int(opt.Height) } - // never resize larger than the original image + // never resize larger than the original image unless specifically allowed if !opt.ScaleUp { if w > imgW { w = imgW @@ -107,10 +109,12 @@ func resizeParams(m image.Image, opt *Options) (w, h int, resize bool) { h = imgH } } + // if requested width and height match the original, skip resizing if (w == imgW || w == 0) && (h == imgH || h == 0) { return 0, 0, false } + return w, h, true } @@ -118,7 +122,7 @@ func resizeParams(m image.Image, opt *Options) (w, h int, resize bool) { // in opt. func transformImage(m image.Image, opt Options) image.Image { // resize if needed - if w, h, resize := resizeParams(m, &opt); resize { + if w, h, resize := resizeParams(m, opt); resize { if opt.Fit { m = imaging.Fit(m, w, h, resampleFilter) } else { diff --git a/transform_test.go b/transform_test.go index 1a59816..ca3f5f0 100644 --- a/transform_test.go +++ b/transform_test.go @@ -40,8 +40,8 @@ func newImage(w, h int, pixels ...color.NRGBA) image.Image { func TestResizeParams(t *testing.T) { src := image.NewNRGBA(image.Rect(0, 0, 64, 128)) tests := []struct { - opt Options - w, h int + opt Options + w, h int resize bool }{ {Options{Width: 0.5}, 32, 0, true}, @@ -52,10 +52,10 @@ func TestResizeParams(t *testing.T) { {Options{Width: 64}, 0, 0, false}, {Options{Height: 128}, 0, 0, false}, } - for ti, tt := range tests { - w, h, resize := resizeParams(src, &tt.opt) + for _, tt := range tests { + w, h, resize := resizeParams(src, tt.opt) if w != tt.w || h != tt.h || resize != tt.resize { - t.Errorf("test %d problem, want: %d,%d,%t got: %d,%d,%t", ti, tt.w, tt.h, tt.resize, w, h, resize) + t.Errorf("resizeParams(%v) returned (%d,%d,%t), want (%d,%d,%t)", tt.opt, w, h, resize, tt.w, tt.h, tt.resize) } } }