processing.go 7.1 KB

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