processing.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package processing
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime"
  6. log "github.com/sirupsen/logrus"
  7. "github.com/imgproxy/imgproxy/v3/config"
  8. "github.com/imgproxy/imgproxy/v3/imagedata"
  9. "github.com/imgproxy/imgproxy/v3/imagetype"
  10. "github.com/imgproxy/imgproxy/v3/imath"
  11. "github.com/imgproxy/imgproxy/v3/options"
  12. "github.com/imgproxy/imgproxy/v3/router"
  13. "github.com/imgproxy/imgproxy/v3/security"
  14. "github.com/imgproxy/imgproxy/v3/vips"
  15. )
  16. var mainPipeline = pipeline{
  17. trim,
  18. prepare,
  19. scaleOnLoad,
  20. importColorProfile,
  21. scale,
  22. rotateAndFlip,
  23. crop,
  24. fixWebpSize,
  25. exportColorProfile,
  26. applyFilters,
  27. extend,
  28. padding,
  29. flatten,
  30. watermark,
  31. finalize,
  32. }
  33. func imageTypeGoodForWeb(imgtype imagetype.Type) bool {
  34. return imgtype != imagetype.TIFF &&
  35. imgtype != imagetype.BMP
  36. }
  37. // src - the source image format
  38. // dst - what the user specified
  39. // want - what we want switch to
  40. func canSwitchFormat(src, dst, want imagetype.Type) bool {
  41. // If the format we want is not supported, we can't switch to it anyway
  42. return vips.SupportsSave(want) &&
  43. // if src format does't support animation, we can switch to whatever we want
  44. (!src.SupportsAnimation() ||
  45. // if user specified the format and it doesn't support animation, we can switch to whatever we want
  46. (dst != imagetype.Unknown && !dst.SupportsAnimation()) ||
  47. // if the format we want supports animation, we can switch in any case
  48. want.SupportsAnimation())
  49. }
  50. func canFitToBytes(imgtype imagetype.Type) bool {
  51. switch imgtype {
  52. case imagetype.JPEG, imagetype.WEBP, imagetype.AVIF, imagetype.TIFF:
  53. return true
  54. default:
  55. return false
  56. }
  57. }
  58. func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  59. if po.Trim.Enabled {
  60. log.Warning("Trim is not supported for animated images")
  61. po.Trim.Enabled = false
  62. }
  63. imgWidth := img.Width()
  64. frameHeight, err := img.GetInt("page-height")
  65. if err != nil {
  66. return err
  67. }
  68. framesCount := imath.Min(img.Height()/frameHeight, config.MaxAnimationFrames)
  69. // Double check dimensions because animated image has many frames
  70. if err = security.CheckDimensions(imgWidth, frameHeight*framesCount); err != nil {
  71. return err
  72. }
  73. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  74. if nPages, _ := img.GetIntDefault("n-pages", 0); nPages > framesCount {
  75. // Load only the needed frames
  76. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  77. return err
  78. }
  79. }
  80. delay, err := img.GetIntSliceDefault("delay", nil)
  81. if err != nil {
  82. return err
  83. }
  84. loop, err := img.GetIntDefault("loop", 0)
  85. if err != nil {
  86. return err
  87. }
  88. // Legacy fields
  89. // TODO: remove this in major update
  90. gifLoop, err := img.GetIntDefault("gif-loop", -1)
  91. if err != nil {
  92. return err
  93. }
  94. gifDelay, err := img.GetIntDefault("gif-delay", -1)
  95. if err != nil {
  96. return err
  97. }
  98. watermarkEnabled := po.Watermark.Enabled
  99. po.Watermark.Enabled = false
  100. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  101. frames := make([]*vips.Image, framesCount)
  102. defer func() {
  103. for _, frame := range frames {
  104. if frame != nil {
  105. frame.Clear()
  106. }
  107. }
  108. }()
  109. for i := 0; i < framesCount; i++ {
  110. frame := new(vips.Image)
  111. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  112. return err
  113. }
  114. frames[i] = frame
  115. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  116. return err
  117. }
  118. }
  119. if err = img.Arrayjoin(frames); err != nil {
  120. return err
  121. }
  122. if watermarkEnabled && imagedata.Watermark != nil {
  123. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, framesCount); err != nil {
  124. return err
  125. }
  126. }
  127. if err = img.CastUchar(); err != nil {
  128. return err
  129. }
  130. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  131. return err
  132. }
  133. if len(delay) == 0 {
  134. delay = make([]int, framesCount)
  135. for i := range delay {
  136. delay[i] = 40
  137. }
  138. } else if len(delay) > framesCount {
  139. delay = delay[:framesCount]
  140. }
  141. img.SetInt("page-height", frames[0].Height())
  142. img.SetIntSlice("delay", delay)
  143. img.SetInt("loop", loop)
  144. img.SetInt("n-pages", framesCount)
  145. // Legacy fields
  146. // TODO: remove this in major update
  147. if gifLoop >= 0 {
  148. img.SetInt("gif-loop", gifLoop)
  149. }
  150. if gifDelay >= 0 {
  151. img.SetInt("gif-delay", gifDelay)
  152. }
  153. return nil
  154. }
  155. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (*imagedata.ImageData, error) {
  156. var diff float64
  157. quality := po.GetQuality()
  158. for {
  159. imgdata, err := img.Save(po.Format, quality)
  160. if len(imgdata.Data) <= po.MaxBytes || quality <= 10 || err != nil {
  161. return imgdata, err
  162. }
  163. imgdata.Close()
  164. router.CheckTimeout(ctx)
  165. delta := float64(len(imgdata.Data)) / float64(po.MaxBytes)
  166. switch {
  167. case delta > 3:
  168. diff = 0.25
  169. case delta > 1.5:
  170. diff = 0.5
  171. default:
  172. diff = 0.75
  173. }
  174. quality = int(float64(quality) * diff)
  175. }
  176. }
  177. func ProcessImage(ctx context.Context, imgdata *imagedata.ImageData, po *options.ProcessingOptions) (*imagedata.ImageData, error) {
  178. runtime.LockOSThread()
  179. defer runtime.UnlockOSThread()
  180. defer vips.Cleanup()
  181. switch {
  182. case po.Format == imagetype.Unknown:
  183. switch {
  184. case po.PreferAvif && canSwitchFormat(imgdata.Type, imagetype.Unknown, imagetype.AVIF):
  185. po.Format = imagetype.AVIF
  186. case po.PreferWebP && canSwitchFormat(imgdata.Type, imagetype.Unknown, imagetype.WEBP):
  187. po.Format = imagetype.WEBP
  188. case vips.SupportsSave(imgdata.Type) && imageTypeGoodForWeb(imgdata.Type):
  189. po.Format = imgdata.Type
  190. default:
  191. po.Format = imagetype.JPEG
  192. }
  193. case po.EnforceAvif && canSwitchFormat(imgdata.Type, po.Format, imagetype.AVIF):
  194. po.Format = imagetype.AVIF
  195. case po.EnforceWebP && canSwitchFormat(imgdata.Type, po.Format, imagetype.WEBP):
  196. po.Format = imagetype.WEBP
  197. }
  198. if !vips.SupportsSave(po.Format) {
  199. return nil, fmt.Errorf("Can't save %s, probably not supported by your libvips", po.Format)
  200. }
  201. animationSupport := config.MaxAnimationFrames > 1 && imgdata.Type.SupportsAnimation() && po.Format.SupportsAnimation()
  202. pages := 1
  203. if animationSupport {
  204. pages = -1
  205. }
  206. img := new(vips.Image)
  207. defer img.Clear()
  208. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  209. return nil, err
  210. }
  211. if animationSupport && img.IsAnimated() {
  212. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  213. return nil, err
  214. }
  215. } else {
  216. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  217. return nil, err
  218. }
  219. }
  220. if err := copyMemoryAndCheckTimeout(ctx, img); err != nil {
  221. return nil, err
  222. }
  223. if po.MaxBytes > 0 && canFitToBytes(po.Format) {
  224. return saveImageToFitBytes(ctx, po, img)
  225. }
  226. return img.Save(po.Format, po.GetQuality())
  227. }