scale_on_load.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package processing
  2. import (
  3. "math"
  4. "github.com/imgproxy/imgproxy/v3/config"
  5. "github.com/imgproxy/imgproxy/v3/imagedata"
  6. "github.com/imgproxy/imgproxy/v3/imagetype"
  7. "github.com/imgproxy/imgproxy/v3/imath"
  8. "github.com/imgproxy/imgproxy/v3/options"
  9. "github.com/imgproxy/imgproxy/v3/vips"
  10. )
  11. func canScaleOnLoad(imgtype imagetype.Type, scale float64) bool {
  12. if imgtype == imagetype.SVG {
  13. return true
  14. }
  15. if config.DisableShrinkOnLoad || scale >= 1 {
  16. return false
  17. }
  18. return imgtype == imagetype.JPEG || imgtype == imagetype.WEBP
  19. }
  20. func calcJpegShink(scale float64, imgtype imagetype.Type) int {
  21. shrink := int(1.0 / scale)
  22. switch {
  23. case shrink >= 8:
  24. return 8
  25. case shrink >= 4:
  26. return 4
  27. case shrink >= 2:
  28. return 2
  29. }
  30. return 1
  31. }
  32. func scaleOnLoad(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  33. prescale := math.Max(pctx.wscale, pctx.hscale)
  34. if pctx.trimmed || prescale == 1 || imgdata == nil || !canScaleOnLoad(pctx.imgtype, prescale) {
  35. return nil
  36. }
  37. jpegShrink := calcJpegShink(prescale, pctx.imgtype)
  38. if pctx.imgtype == imagetype.JPEG && jpegShrink == 1 {
  39. return nil
  40. }
  41. if err := img.Load(imgdata, jpegShrink, prescale, 1); err != nil {
  42. return err
  43. }
  44. // Update scales after scale-on-load
  45. newWidth, newHeight, _, _ := extractMeta(img, po.Rotate, po.AutoRotate)
  46. pctx.wscale = float64(pctx.srcWidth) * pctx.wscale / float64(newWidth)
  47. if pctx.srcWidth == imath.Scale(pctx.srcWidth, pctx.wscale) {
  48. pctx.wscale = 1.0
  49. }
  50. pctx.hscale = float64(pctx.srcHeight) * pctx.hscale / float64(newHeight)
  51. if pctx.srcHeight == imath.Scale(pctx.srcHeight, pctx.hscale) {
  52. pctx.hscale = 1.0
  53. }
  54. return nil
  55. }