From 7e8eb0479702a89d0ef1919c1e611da8e53fc2f2 Mon Sep 17 00:00:00 2001 From: Michael Duergner Date: Mon, 10 Sep 2018 12:53:19 +0200 Subject: [PATCH] #101 Limit min width to original image width The first implementation of the min width parameter did not care about whether the original image could actually support a crop of this size. The resulting image min width now is capped by the original image min width. If one needs to have a bigger resulting image it needs to be combined with a resize filter. --- filters/cropbyfocalpoint.go | 15 +++++++++++---- filters/cropbyfocalpoint_test.go | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/filters/cropbyfocalpoint.go b/filters/cropbyfocalpoint.go index 176917b..f00e0b9 100644 --- a/filters/cropbyfocalpoint.go +++ b/filters/cropbyfocalpoint.go @@ -17,6 +17,13 @@ type cropByFocalPoint struct { minWidth int } +func Min(x, y int) int { + if x < y { + return x + } + return y +} + // NewCropByFocalPoint creates a new filter of this type func NewCropByFocalPoint() filters.Spec { return &cropByFocalPoint{} @@ -57,10 +64,10 @@ func (f *cropByFocalPoint) CreateOptions(imageContext *ImageFilterContext) (*bim if f.minWidth != -1 { minHeight := int(f.aspectRatio * float64(f.minWidth)) - minX := int(float64(f.minWidth) * f.targetX) - maxX := imageSize.Width - int(float64(f.minWidth) * (1 - f.targetX)) - minY := int(float64(minHeight) * f.targetY) - maxY := imageSize.Height - int(float64(minHeight) * (1 - f.targetY)) + minX := int(float64(Min(f.minWidth, imageSize.Width)) * f.targetX) + maxX := imageSize.Width - int(float64(Min(f.minWidth, imageSize.Width)) * (1 - f.targetX)) + minY := int(float64(Min(minHeight, imageSize.Height)) * f.targetY) + maxY := imageSize.Height - int(float64(Min(minHeight, imageSize.Height)) * (1 - f.targetY)) if x < minX { x = minX diff --git a/filters/cropbyfocalpoint_test.go b/filters/cropbyfocalpoint_test.go index a568e6d..d9a3cfb 100644 --- a/filters/cropbyfocalpoint_test.go +++ b/filters/cropbyfocalpoint_test.go @@ -70,6 +70,24 @@ func TestCropByFocalPoint_CreateOptions_MinWidth(t *testing.T) { assert.Equal(t, 250, options.AreaHeight) assert.Equal(t, 209, options.Top) assert.Equal(t, 0, options.Left) + + c = cropByFocalPoint{targetX: 0.5, targetY: 0.5, aspectRatio: 0.5, minWidth: 1500.0} + + options, _ = c.CreateOptions(buildParameters(fc, image)) + + assert.Equal(t, 1000, options.AreaWidth) + assert.Equal(t, 500, options.AreaHeight) + assert.Equal(t, 84, options.Top) + assert.Equal(t, 0, options.Left) + + c = cropByFocalPoint{targetX: 0.5, targetY: 0.5, aspectRatio: 1.0, minWidth: 1500.0} + + options, _ = c.CreateOptions(buildParameters(fc, image)) + + assert.Equal(t, 668, options.AreaWidth) + assert.Equal(t, 668, options.AreaHeight) + assert.Equal(t, 0, options.Top) + assert.Equal(t, 166, options.Left) } func TestCropByFocalPoint_CreateOptions_MissingPathParam(t *testing.T) {