fix_size.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package processing
  2. import (
  3. "math"
  4. "github.com/imgproxy/imgproxy/v3/imagedata"
  5. "github.com/imgproxy/imgproxy/v3/imagetype"
  6. "github.com/imgproxy/imgproxy/v3/imath"
  7. "github.com/imgproxy/imgproxy/v3/options"
  8. "github.com/imgproxy/imgproxy/v3/vips"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. const (
  12. // https://chromium.googlesource.com/webm/libwebp/+/refs/heads/master/src/webp/encode.h#529
  13. webpMaxDimension = 16383.0
  14. gifMaxDimension = 65535.0
  15. icoMaxDimension = 256.0
  16. )
  17. func fixWebpSize(img *vips.Image) error {
  18. webpLimitShrink := float64(imath.Max(img.Width(), img.Height())) / webpMaxDimension
  19. if webpLimitShrink <= 1.0 {
  20. return nil
  21. }
  22. scale := 1.0 / webpLimitShrink
  23. if err := img.Resize(scale, scale); err != nil {
  24. return err
  25. }
  26. log.Warningf("WebP dimension size is limited to %d. The image is rescaled to %dx%d", int(webpMaxDimension), img.Width(), img.Height())
  27. return img.CopyMemory()
  28. }
  29. func fixGifSize(img *vips.Image) error {
  30. gifMaxResolution := float64(vips.GifResolutionLimit())
  31. gifResLimitShrink := float64(img.Width()*img.Height()) / gifMaxResolution
  32. gifDimLimitShrink := float64(imath.Max(img.Width(), img.Height())) / gifMaxDimension
  33. gifLimitShrink := math.Max(gifResLimitShrink, gifDimLimitShrink)
  34. if gifLimitShrink <= 1.0 {
  35. return nil
  36. }
  37. scale := math.Sqrt(1.0 / gifLimitShrink)
  38. if err := img.Resize(scale, scale); err != nil {
  39. return err
  40. }
  41. log.Warningf("GIF resolution is limited to %d and dimension size is limited to %d. The image is rescaled to %dx%d", int(gifMaxResolution), int(gifMaxDimension), img.Width(), img.Height())
  42. return img.CopyMemory()
  43. }
  44. func fixIcoSize(img *vips.Image) error {
  45. icoLimitShrink := float64(imath.Max(img.Width(), img.Height())) / icoMaxDimension
  46. if icoLimitShrink <= 1.0 {
  47. return nil
  48. }
  49. scale := 1.0 / icoLimitShrink
  50. if err := img.Resize(scale, scale); err != nil {
  51. return err
  52. }
  53. log.Warningf("ICO dimension size is limited to %d. The image is rescaled to %dx%d", int(icoMaxDimension), img.Width(), img.Height())
  54. return img.CopyMemory()
  55. }
  56. func fixSize(pctx *pipelineContext, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  57. switch po.Format {
  58. case imagetype.WEBP:
  59. return fixWebpSize(img)
  60. case imagetype.GIF:
  61. return fixGifSize(img)
  62. case imagetype.ICO:
  63. return fixIcoSize(img)
  64. }
  65. return nil
  66. }