0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-30 22:34:18 -05:00

Extract resizeParams method.

This commit is contained in:
orian 2015-10-14 18:15:57 +02:00
parent 5f5df0c860
commit 431898ec9a
2 changed files with 29 additions and 6 deletions

View file

@ -79,13 +79,10 @@ func Transform(img []byte, opt Options) ([]byte, error) {
return buf.Bytes(), nil return buf.Bytes(), nil
} }
// transformImage modifies the image m based on the transformations specified func resizeParams(m image.Image, opt *Options) (w, h int) {
// in opt.
func transformImage(m image.Image, opt Options) image.Image {
// convert percentage width and height values to absolute values // convert percentage width and height values to absolute values
imgW := m.Bounds().Max.X - m.Bounds().Min.X imgW := m.Bounds().Max.X - m.Bounds().Min.X
imgH := m.Bounds().Max.Y - m.Bounds().Min.Y imgH := m.Bounds().Max.Y - m.Bounds().Min.Y
var w, h int
if 0 < opt.Width && opt.Width < 1 { if 0 < opt.Width && opt.Width < 1 {
w = int(float64(imgW) * opt.Width) w = int(float64(imgW) * opt.Width)
} else if opt.Width < 0 { } else if opt.Width < 0 {
@ -110,9 +107,14 @@ func transformImage(m image.Image, opt Options) image.Image {
h = imgH h = imgH
} }
} }
return
}
// resize // transformImage modifies the image m based on the transformations specified
if w != 0 || h != 0 { // 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 { if opt.Fit {
m = imaging.Fit(m, w, h, resampleFilter) m = imaging.Fit(m, w, h, resampleFilter)
} else { } else {

View file

@ -37,6 +37,27 @@ func newImage(w, h int, pixels ...color.NRGBA) image.Image {
return m 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) { func TestTransform(t *testing.T) {
src := newImage(2, 2, red, green, blue, yellow) src := newImage(2, 2, red, green, blue, yellow)