Skip to content

Commit

Permalink
feat: crop larger image
Browse files Browse the repository at this point in the history
  • Loading branch information
KagChi committed Nov 19, 2023
1 parent 4e598bf commit e3220b4
Showing 1 changed file with 36 additions and 19 deletions.
55 changes: 36 additions & 19 deletions impl/image_resizer/client/image_resizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"encoding/hex"
"errors"
"fmt"
"math"

"github.com/davidbyttow/govips/v2/vips"
resty "github.com/go-resty/resty/v2"
)
Expand All @@ -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) {
Expand Down

0 comments on commit e3220b4

Please sign in to comment.