processing.go 6.7 KB

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