Add min dimension logic to smartcrop

The pre-crop operations will sometime yield
an image that is already the correct size or
1 pixel smaller (due to rounding error). Currently,
bimg will try to smart crop anyways and yield a
"bad extract area" error.
master
Patrick Zhang 7 years ago
parent 15cd115607
commit ba2a6715ee

@ -256,9 +256,19 @@ func extractOrEmbedImage(image *C.VipsImage, o Options) (*C.VipsImage, error) {
switch {
case o.Gravity == GravitySmart, o.SmartCrop:
image, err = vipsSmartCrop(image, o.Width, o.Height)
// it's already at an appropriate size, return immediately
if inWidth <= o.Width && inHeight <= o.Height {
break
}
width := int(math.Min(float64(inWidth), float64(o.Width)))
height := int(math.Min(float64(inHeight), float64(o.Height)))
image, err = vipsSmartCrop(image, width, height)
break
case o.Crop:
// it's already at an appropriate size, return immediately
if inWidth <= o.Width && inHeight <= o.Height {
break
}
width := int(math.Min(float64(inWidth), float64(o.Width)))
height := int(math.Min(float64(inHeight), float64(o.Height)))
left, top := calculateCrop(inWidth, inHeight, o.Width, o.Height, o.Gravity)

@ -590,6 +590,76 @@ func TestIfBothSmartCropOptionsAreIdentical(t *testing.T) {
}
}
func TestSkipCropIfTooSmall(t *testing.T) {
testCases := [] struct {
name string
options Options
} {
{
name: "smart crop",
options: Options{
Width: 140,
Height: 140,
Crop: true,
Gravity: GravitySmart,
},
},
{
name: "centre crop",
options: Options{
Width: 140,
Height: 140,
Crop: true,
Gravity: GravityCentre,
},
},
{
name: "embed",
options: Options{
Width: 140,
Height: 140,
Embed: true,
},
},
{
name: "extract",
options: Options{
Top: 0,
Left: 0,
AreaWidth: 140,
AreaHeight: 140,
},
},
}
testImg, err := os.Open("testdata/test_bad_extract_area.jpg")
if err != nil {
t.Fatal(err)
}
defer testImg.Close()
testImgByte, err := ioutil.ReadAll(testImg)
if err != nil {
t.Fatal(err)
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
croppedImage, err := Resize(testImgByte, tc.options)
if err != nil {
t.Fatal(err)
}
size, _ := Size(croppedImage)
if tc.options.Height-size.Height > 1 || tc.options.Width-size.Width > 1 {
t.Fatalf("Invalid image size: %dx%d", size.Width, size.Height)
}
t.Logf("size for %s is %dx%d", tc.name, size.Width, size.Height)
})
}
}
func runBenchmarkResize(file string, o Options, b *testing.B) {
buf, _ := Read(path.Join("testdata", file))

Binary file not shown.

After

Width:  |  Height:  |  Size: 312 KiB

Loading…
Cancel
Save