diff --git a/transform.go b/transform.go index f199eb3..79c56db 100644 --- a/transform.go +++ b/transform.go @@ -79,13 +79,10 @@ func Transform(img []byte, opt Options) ([]byte, error) { return buf.Bytes(), nil } -// transformImage modifies the image m based on the transformations specified -// in opt. -func transformImage(m image.Image, opt Options) image.Image { +func resizeParams(m image.Image, opt *Options) (w, h int) { // 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 - var w, h int if 0 < opt.Width && opt.Width < 1 { w = int(float64(imgW) * opt.Width) } else if opt.Width < 0 { @@ -110,9 +107,14 @@ func transformImage(m image.Image, opt Options) image.Image { h = imgH } } + return +} - // resize - if w != 0 || h != 0 { +// transformImage modifies the image m based on the transformations specified +// in opt. +func transformImage(m image.Image, opt Options) image.Image { + // resize if needed + if w, h := resizeParams(m, &opt); w != 0 || h != 0 { if opt.Fit { m = imaging.Fit(m, w, h, resampleFilter) } else { diff --git a/transform_test.go b/transform_test.go index 3c4b465..c4c0bf0 100644 --- a/transform_test.go +++ b/transform_test.go @@ -37,6 +37,27 @@ func newImage(w, h int, pixels ...color.NRGBA) image.Image { return m } +func TestResizeParams(t *testing.T) { + src := image.NewNRGBA(image.Rect(0, 0, 64, 128)) + tests := []struct { + opt Options + w,h int + }{ + {Options{Width:0.5}, 32, 0}, + {Options{Height:0.5}, 0, 64}, + {Options{Width:0.5, Height:0.5}, 32, 64}, + {Options{Width:100, Height: 200}, 64, 128}, + {Options{Width:64}, 64, 0}, + {Options{Height:128}, 0, 128}, + } + for ti,tt := range tests { + w,h := resizeParams(src, &tt.opt) + if w != tt.w || h!= tt.h { + t.Errorf("test %d problem, want: %d,%d got: %d,%d", ti, tt.w, tt.h, w, h) + } + } +} + func TestTransform(t *testing.T) { src := newImage(2, 2, red, green, blue, yellow)