crop.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package processing
  2. import (
  3. "github.com/imgproxy/imgproxy/v3/imath"
  4. "github.com/imgproxy/imgproxy/v3/options"
  5. "github.com/imgproxy/imgproxy/v3/vips"
  6. )
  7. func cropImage(img *vips.Image, cropWidth, cropHeight int, gravity *options.GravityOptions, offsetScale float64) error {
  8. if cropWidth == 0 && cropHeight == 0 {
  9. return nil
  10. }
  11. imgWidth, imgHeight := img.Width(), img.Height()
  12. cropWidth = imath.MinNonZero(cropWidth, imgWidth)
  13. cropHeight = imath.MinNonZero(cropHeight, imgHeight)
  14. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  15. return nil
  16. }
  17. if gravity.Type == options.GravitySmart {
  18. if err := img.CopyMemory(); err != nil {
  19. return err
  20. }
  21. return img.SmartCrop(cropWidth, cropHeight)
  22. }
  23. left, top := calcPosition(imgWidth, imgHeight, cropWidth, cropHeight, gravity, offsetScale, false)
  24. return img.Crop(left, top, cropWidth, cropHeight)
  25. }
  26. func (p *Processor) crop(c *Context) error {
  27. width, height := c.CropWidth, c.CropHeight
  28. opts := c.CropGravity
  29. opts.RotateAndFlip(c.Angle, c.Flip)
  30. opts.RotateAndFlip(c.PO.Rotate, false)
  31. if (c.Angle+c.PO.Rotate)%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. return cropImage(c.Img, c.ResultCropWidth, c.ResultCropHeight, &c.PO.Gravity, c.DprScale)
  39. }