crop.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package processing
  2. import (
  3. "github.com/imgproxy/imgproxy/v3/imath"
  4. "github.com/imgproxy/imgproxy/v3/vips"
  5. )
  6. func cropImage(img *vips.Image, cropWidth, cropHeight int, gravity *GravityOptions, offsetScale float64) error {
  7. if cropWidth == 0 && cropHeight == 0 {
  8. return nil
  9. }
  10. imgWidth, imgHeight := img.Width(), img.Height()
  11. cropWidth = imath.MinNonZero(cropWidth, imgWidth)
  12. cropHeight = imath.MinNonZero(cropHeight, imgHeight)
  13. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  14. return nil
  15. }
  16. if gravity.Type == GravitySmart {
  17. if err := img.CopyMemory(); err != nil {
  18. return err
  19. }
  20. return img.SmartCrop(cropWidth, cropHeight)
  21. }
  22. left, top := calcPosition(imgWidth, imgHeight, cropWidth, cropHeight, gravity, offsetScale, false)
  23. return img.Crop(left, top, cropWidth, cropHeight)
  24. }
  25. func (p *Processor) crop(c *Context) error {
  26. width, height := c.CropWidth, c.CropHeight
  27. rotateAngle := c.PO.Rotate()
  28. opts := c.CropGravity
  29. opts.RotateAndFlip(c.Angle, c.Flip)
  30. opts.RotateAndFlip(rotateAngle, false)
  31. if (c.Angle+rotateAngle)%180 == 90 {
  32. width, height = height, width
  33. }
  34. // Since we crop before scaling, we shouldn't consider DPR
  35. return cropImage(c.Img, width, height, &opts, 1.0)
  36. }
  37. func (p *Processor) cropToResult(c *Context) error {
  38. gravity := c.PO.Gravity()
  39. return cropImage(c.Img, c.ResultCropWidth, c.ResultCropHeight, &gravity, c.DprScale)
  40. }