trim.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package processing
  2. import (
  3. "math"
  4. "github.com/imgproxy/imgproxy/v3/imagedata"
  5. "github.com/imgproxy/imgproxy/v3/options"
  6. "github.com/imgproxy/imgproxy/v3/vips"
  7. )
  8. func trim(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  9. if !po.Trim.Enabled {
  10. return nil
  11. }
  12. // The size of a vector image is not checked during download, yet it can be very large.
  13. // So we should scale it down to the maximum allowed resolution
  14. if imgdata != nil && imgdata.Type.IsVector() {
  15. if resolution := img.Width() * img.Height(); resolution > po.SecurityOptions.MaxSrcResolution {
  16. scale := math.Sqrt(float64(po.SecurityOptions.MaxSrcResolution) / float64(resolution))
  17. if err := img.Load(imgdata, 1, scale, 1); err != nil {
  18. return err
  19. }
  20. }
  21. }
  22. // We need to import color profile before trim
  23. if err := importColorProfile(pctx, img, po, imgdata); err != nil {
  24. return err
  25. }
  26. if err := img.Trim(po.Trim.Threshold, po.Trim.Smart, po.Trim.Color, po.Trim.EqualHor, po.Trim.EqualVer); err != nil {
  27. return err
  28. }
  29. if err := img.CopyMemory(); err != nil {
  30. return err
  31. }
  32. pctx.trimmed = true
  33. return nil
  34. }