1
0

crop.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. return img.SmartCrop(cropWidth, cropHeight)
  23. }
  24. left, top := calcPosition(imgWidth, imgHeight, cropWidth, cropHeight, gravity, false)
  25. return img.Crop(left, top, cropWidth, cropHeight)
  26. }
  27. func crop(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  28. width, height := pctx.cropWidth, pctx.cropHeight
  29. opts := pctx.cropGravity
  30. opts.RotateAndFlip(pctx.angle, pctx.flip)
  31. opts.RotateAndFlip(po.Rotate, false)
  32. if (pctx.angle+po.Rotate)%180 == 90 {
  33. width, height = height, width
  34. }
  35. return cropImage(img, width, height, &opts)
  36. }
  37. func cropToResult(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  38. // Crop image to the result size
  39. resultWidth, resultHeight := resultSize(po)
  40. if po.ResizingType == options.ResizeFillDown {
  41. diffW := float64(resultWidth) / float64(img.Width())
  42. diffH := float64(resultHeight) / float64(img.Height())
  43. switch {
  44. case diffW > diffH && diffW > 1.0:
  45. resultHeight = imath.Scale(img.Width(), float64(resultHeight)/float64(resultWidth))
  46. resultWidth = img.Width()
  47. case diffH > diffW && diffH > 1.0:
  48. resultWidth = imath.Scale(img.Height(), float64(resultWidth)/float64(resultHeight))
  49. resultHeight = img.Height()
  50. }
  51. }
  52. return cropImage(img, resultWidth, resultHeight, &po.Gravity)
  53. }