From e3220b41113825a2185ddcd474f71ef85f3b48c1 Mon Sep 17 00:00:00 2001 From: kagchi Date: Sun, 19 Nov 2023 11:12:44 +0700 Subject: [PATCH] feat: crop larger image --- impl/image_resizer/client/image_resizer.go | 55 ++++++++++++++-------- 1 file changed, 36 insertions(+), 19 deletions(-) diff --git a/impl/image_resizer/client/image_resizer.go b/impl/image_resizer/client/image_resizer.go index 8b117c9..928b59f 100644 --- a/impl/image_resizer/client/image_resizer.go +++ b/impl/image_resizer/client/image_resizer.go @@ -6,6 +6,8 @@ import ( "encoding/hex" "errors" "fmt" + "math" + "github.com/davidbyttow/govips/v2/vips" resty "github.com/go-resty/resty/v2" ) @@ -23,30 +25,45 @@ type imageResizerClient struct { } func (i imageResizerClient) ResizeImage(image []byte, width, height int) (result []byte, err error) { - img, err := vips.NewImageFromBuffer(image) - defer img.Close() - if err != nil { - err = errors.New(fmt.Sprintf("unable to read image: %v", err.Error())) - return - } +img, err := vips.NewImageFromBuffer(image) + defer img.Close() + if err != nil { + err = errors.New(fmt.Sprintf("unable to read image: %v", err.Error())) + return + } - // Get original size of image - originalWidth := float64(img.Width()) - originalHeight := float64(img.Height()) + // Get original size of image + originalWidth := float64(img.Width()) + originalHeight := float64(img.Height()) - if err = img.ResizeWithVScale(float64(width)/originalWidth, float64(height)/originalHeight, vips.KernelNearest); err != nil { - return - } + // Calculate scale factors for width and height + scaleWidth := float64(width) / originalWidth + scaleHeight := float64(height) / originalHeight - options := vips.NewJpegExportParams() - options.Quality = 100 - result, _, err = img.ExportJpeg(options) - if err != nil { - err = errors.New(fmt.Sprintf("unable to export image: %v", err)) - return + // Use the smaller scale factor to ensure the entire image fits within the specified dimensions + scaleFactor := math.Min(scaleWidth, scaleHeight) + + if originalWidth == originalHeight { + if err = img.Resize(scaleFactor, vips.KernelNearest); err != nil { + return + } + } else { + // Crop the image to the specified dimensions while maintaining the aspect ratio + if err = img.SmartCrop(width, height, vips.InterestingCentre); err != nil { + return + } } - return + + options := vips.NewJpegExportParams() + options.Quality = 100 + result, _, err = img.ExportJpeg(options) + if err != nil { + err = errors.New(fmt.Sprintf("unable to export image: %v", err)) + return + } + + return } func (i imageResizerClient) GetOriginImage(url string) (result []byte, err error) {