diff --git a/image.go b/image.go index 2836787..6b6e179 100644 --- a/image.go +++ b/image.go @@ -48,6 +48,11 @@ func (i *Image) Extract(top, left, width, height int) ([]byte, error) { AreaWidth: width, AreaHeight: height, } + + if top == 0 && left == 0 { + options.Top = -1 + } + return i.Process(options) } diff --git a/image_test.go b/image_test.go index e396857..b0faff5 100644 --- a/image_test.go +++ b/image_test.go @@ -48,6 +48,20 @@ func TestImageExtract(t *testing.T) { Write("fixtures/test_extract_out.jpg", buf) } +func TestImageExtractZero(t *testing.T) { + buf, err := initImage("test.jpg").Extract(0, 0, 300, 200) + if err != nil { + t.Errorf("Cannot process the image: %s", err) + } + + err = assertSize(buf, 300, 200) + if err != nil { + t.Error(err) + } + + Write("fixtures/test_extract_zero_out.jpg", buf) +} + func TestImageEnlarge(t *testing.T) { buf, err := initImage("test.png").Enlarge(500, 375) if err != nil { diff --git a/resize.go b/resize.go index 87600c2..9c7005e 100644 --- a/resize.go +++ b/resize.go @@ -229,7 +229,7 @@ func extractOrEmbedImage(image *C.VipsImage, o Options) (*C.VipsImage, error) { left, top := (o.Width-inWidth)/2, (o.Height-inHeight)/2 image, err = vipsEmbed(image, left, top, o.Width, o.Height, o.Extend) break - case o.Top > 0 || o.Left > 0: + case o.Top != 0 || o.Left != 0: if o.AreaWidth == 0 { o.AreaHeight = o.Width } diff --git a/vips.go b/vips.go index 248b511..57bca95 100644 --- a/vips.go +++ b/vips.go @@ -8,6 +8,7 @@ import "C" import ( "errors" + "math" "os" "runtime" "strings" @@ -340,6 +341,10 @@ func vipsSave(image *C.VipsImage, o vipsSaveOptions) ([]byte, error) { return buf, nil } +func max(x int) int { + return int(math.Max(float64(x), 0)) +} + func vipsExtract(image *C.VipsImage, left, top, width, height int) (*C.VipsImage, error) { var buf *C.VipsImage defer C.g_object_unref(C.gpointer(image)) @@ -348,6 +353,7 @@ func vipsExtract(image *C.VipsImage, left, top, width, height int) (*C.VipsImage return nil, errors.New("Maximum image size exceeded") } + top, left = max(top), max(left) err := C.vips_extract_area_bridge(image, &buf, C.int(left), C.int(top), C.int(width), C.int(height)) if err != 0 { return nil, catchVipsError()