crop.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package processing
  2. import (
  3. "github.com/imgproxy/imgproxy/v3/imagedata"
  4. "github.com/imgproxy/imgproxy/v3/imath"
  5. "github.com/imgproxy/imgproxy/v3/options"
  6. "github.com/imgproxy/imgproxy/v3/vips"
  7. )
  8. func cropImage(img *vips.Image, cropWidth, cropHeight int, gravity *options.GravityOptions) error {
  9. if cropWidth == 0 && cropHeight == 0 {
  10. return nil
  11. }
  12. imgWidth, imgHeight := img.Width(), img.Height()
  13. cropWidth = imath.MinNonZero(cropWidth, imgWidth)
  14. cropHeight = imath.MinNonZero(cropHeight, imgHeight)
  15. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  16. return nil
  17. }
  18. if gravity.Type == options.GravitySmart {
  19. if err := img.CopyMemory(); err != nil {
  20. return err
  21. }
  22. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  23. return err
  24. }
  25. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  26. // so we have to copy memory after it
  27. return img.CopyMemory()
  28. }
  29. left, top := calcPosition(imgWidth, imgHeight, cropWidth, cropHeight, gravity, false)
  30. return img.Crop(left, top, cropWidth, cropHeight)
  31. }
  32. func crop(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  33. if err := cropImage(img, pctx.cropWidth, pctx.cropHeight, &pctx.cropGravity); err != nil {
  34. return err
  35. }
  36. // Crop image to the result size
  37. resultWidth := imath.Scale(po.Width, po.Dpr)
  38. resultHeight := imath.Scale(po.Height, po.Dpr)
  39. if po.ResizingType == options.ResizeFillDown {
  40. if resultWidth > img.Width() {
  41. resultHeight = imath.Scale(resultHeight, float64(img.Width())/float64(resultWidth))
  42. resultWidth = img.Width()
  43. }
  44. if resultHeight > img.Height() {
  45. resultWidth = imath.Scale(resultWidth, float64(img.Height())/float64(resultHeight))
  46. resultHeight = img.Height()
  47. }
  48. }
  49. return cropImage(img, resultWidth, resultHeight, &po.Gravity)
  50. }