processing.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. watermarkEnabled := po.Watermark.Enabled
  97. po.Watermark.Enabled = false
  98. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  99. frames := make([]*vips.Image, framesCount)
  100. defer func() {
  101. for _, frame := range frames {
  102. if frame != nil {
  103. frame.Clear()
  104. }
  105. }
  106. }()
  107. for i := 0; i < framesCount; i++ {
  108. frame := new(vips.Image)
  109. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  110. return err
  111. }
  112. frames[i] = frame
  113. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  114. return err
  115. }
  116. }
  117. if err = img.Arrayjoin(frames); err != nil {
  118. return err
  119. }
  120. if watermarkEnabled && imagedata.Watermark != nil {
  121. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, framesCount); err != nil {
  122. return err
  123. }
  124. }
  125. if err = img.CastUchar(); err != nil {
  126. return err
  127. }
  128. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  129. return err
  130. }
  131. if len(delay) == 0 {
  132. delay = make([]int, framesCount)
  133. for i := range delay {
  134. delay[i] = 40
  135. }
  136. } else if len(delay) > framesCount {
  137. delay = delay[:framesCount]
  138. }
  139. img.SetInt("page-height", frames[0].Height())
  140. img.SetIntSlice("delay", delay)
  141. img.SetInt("loop", loop)
  142. img.SetInt("n-pages", framesCount)
  143. return nil
  144. }
  145. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (*imagedata.ImageData, error) {
  146. var diff float64
  147. quality := po.GetQuality()
  148. for {
  149. imgdata, err := img.Save(po.Format, quality)
  150. if len(imgdata.Data) <= po.MaxBytes || quality <= 10 || err != nil {
  151. return imgdata, err
  152. }
  153. imgdata.Close()
  154. router.CheckTimeout(ctx)
  155. delta := float64(len(imgdata.Data)) / float64(po.MaxBytes)
  156. switch {
  157. case delta > 3:
  158. diff = 0.25
  159. case delta > 1.5:
  160. diff = 0.5
  161. default:
  162. diff = 0.75
  163. }
  164. quality = int(float64(quality) * diff)
  165. }
  166. }
  167. func ProcessImage(ctx context.Context, imgdata *imagedata.ImageData, po *options.ProcessingOptions) (*imagedata.ImageData, error) {
  168. runtime.LockOSThread()
  169. defer runtime.UnlockOSThread()
  170. defer vips.Cleanup()
  171. switch {
  172. case po.Format == imagetype.Unknown:
  173. switch {
  174. case po.PreferAvif && canSwitchFormat(imgdata.Type, imagetype.Unknown, imagetype.AVIF):
  175. po.Format = imagetype.AVIF
  176. case po.PreferWebP && canSwitchFormat(imgdata.Type, imagetype.Unknown, imagetype.WEBP):
  177. po.Format = imagetype.WEBP
  178. case vips.SupportsSave(imgdata.Type) && imageTypeGoodForWeb(imgdata.Type):
  179. po.Format = imgdata.Type
  180. default:
  181. po.Format = imagetype.JPEG
  182. }
  183. case po.EnforceAvif && canSwitchFormat(imgdata.Type, po.Format, imagetype.AVIF):
  184. po.Format = imagetype.AVIF
  185. case po.EnforceWebP && canSwitchFormat(imgdata.Type, po.Format, imagetype.WEBP):
  186. po.Format = imagetype.WEBP
  187. }
  188. if !vips.SupportsSave(po.Format) {
  189. return nil, fmt.Errorf("Can't save %s, probably not supported by your libvips", po.Format)
  190. }
  191. animationSupport := config.MaxAnimationFrames > 1 && imgdata.Type.SupportsAnimation() && po.Format.SupportsAnimation()
  192. pages := 1
  193. if animationSupport {
  194. pages = -1
  195. }
  196. img := new(vips.Image)
  197. defer img.Clear()
  198. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  199. return nil, err
  200. }
  201. originWidth, originHeight := getImageSize(img)
  202. if animationSupport && img.IsAnimated() {
  203. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  204. return nil, err
  205. }
  206. } else {
  207. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  208. return nil, err
  209. }
  210. }
  211. if err := copyMemoryAndCheckTimeout(ctx, img); err != nil {
  212. return nil, err
  213. }
  214. var (
  215. outData *imagedata.ImageData
  216. err error
  217. )
  218. if po.MaxBytes > 0 && canFitToBytes(po.Format) {
  219. outData, err = saveImageToFitBytes(ctx, po, img)
  220. } else {
  221. outData, err = img.Save(po.Format, po.GetQuality())
  222. }
  223. if err == nil {
  224. if outData.Headers == nil {
  225. outData.Headers = make(map[string]string)
  226. }
  227. outData.Headers["X-Origin-Width"] = strconv.Itoa(originWidth)
  228. outData.Headers["X-Origin-Height"] = strconv.Itoa(originHeight)
  229. }
  230. return outData, err
  231. }