diff --git a/options.go b/options.go index 17a1cb4c..7755e47c 100644 --- a/options.go +++ b/options.go @@ -197,6 +197,7 @@ type Options struct { Quality int Compression int Zoom int + Fit bool // Fit image into given dimensions Crop bool SmartCrop bool // Deprecated, use: bimg.Options.Gravity = bimg.GravitySmart Enlarge bool diff --git a/resizer.go b/resizer.go index 98a95ae7..88eb96ed 100644 --- a/resizer.go +++ b/resizer.go @@ -170,7 +170,7 @@ func saveImage(image *C.VipsImage, o Options) ([]byte, error) { } func normalizeOperation(o *Options, inWidth, inHeight int) { - if !o.Force && !o.Crop && !o.Embed && !o.Enlarge && o.Rotate == 0 && (o.Width > 0 || o.Height > 0) { + if !o.Force && !o.Fit && !o.Crop && !o.Embed && !o.Enlarge && o.Rotate == 0 && (o.Width > 0 || o.Height > 0) { o.Force = true } } @@ -443,7 +443,11 @@ func imageCalculations(o *Options, inWidth, inHeight int) float64 { switch { // Fixed width and height case o.Width > 0 && o.Height > 0: - factor = math.Min(xfactor, yfactor) + if o.Crop { + factor = math.Min(xfactor, yfactor) + } else { + factor = math.Max(xfactor, yfactor) + } // Fixed width, auto height case o.Width > 0: if o.Crop { diff --git a/resizer_test.go b/resizer_test.go index a4b54b08..3be04c8d 100644 --- a/resizer_test.go +++ b/resizer_test.go @@ -161,6 +161,36 @@ func TestResizeCustomSizes(t *testing.T) { } } +func TestResizeFit(t *testing.T) { + // see https://github.com/h2non/bimg/issues/257 + buf, _ := Read("testdata/test_fit.png") + forceOptions := []bool{true, false} + + for _, forceOpt := range forceOptions { + opts := Options{Width: 1000, Height: 20, Fit: true, Force: forceOpt} + newImg, err := Resize(buf, opts) + if err != nil { + t.Fatalf("Resize(imgData, %#v) error: %#v", opts, err) + } + + size, _ := Size(newImg) + if !forceOpt && size.Width != 115 { + t.Fatalf("Invalid width (Force=false): %d, expected 115", size.Width) + } + if forceOpt && size.Width != 1000 { + t.Fatalf("Invalid width (Force=true): %d, expected 1000", size.Width) + } + if size.Height != 20 { + t.Fatalf("Invalid width: %d, expected 20", size.Width) + } + + Write(fmt.Sprintf( + "testdata/test_fit_%v_out.png", + forceOpt, + ), newImg) + } +} + func TestResizePrecision(t *testing.T) { // see https://github.com/h2non/bimg/issues/99 img := image.NewGray16(image.Rect(0, 0, 1920, 1080)) diff --git a/testdata/test_fit.png b/testdata/test_fit.png new file mode 100644 index 00000000..5265c4a7 Binary files /dev/null and b/testdata/test_fit.png differ