processing.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package processing
  2. import (
  3. "context"
  4. "errors"
  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. applyFilters,
  27. extend,
  28. extendAspectRatio,
  29. padding,
  30. fixSize,
  31. flatten,
  32. watermark,
  33. }
  34. var finalizePipeline = pipeline{
  35. exportColorProfile,
  36. stripMetadata,
  37. }
  38. func isImageTypePreferred(imgtype imagetype.Type) bool {
  39. for _, t := range config.PreferredFormats {
  40. if imgtype == t {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. func findBestFormat(srcType imagetype.Type, animated, expectAlpha bool) imagetype.Type {
  47. for _, t := range config.PreferredFormats {
  48. if animated && !t.SupportsAnimationSave() {
  49. continue
  50. }
  51. if expectAlpha && !t.SupportsAlpha() {
  52. continue
  53. }
  54. return t
  55. }
  56. return config.PreferredFormats[0]
  57. }
  58. func ValidatePreferredFormats() error {
  59. filtered := config.PreferredFormats[:0]
  60. for _, t := range config.PreferredFormats {
  61. if !vips.SupportsSave(t) {
  62. log.Warnf("%s can't be a preferred format as it's saving is not supported", t)
  63. } else {
  64. filtered = append(filtered, t)
  65. }
  66. }
  67. if len(filtered) == 0 {
  68. return errors.New("No supported preferred formats specified")
  69. }
  70. config.PreferredFormats = filtered
  71. return nil
  72. }
  73. func getImageSize(img *vips.Image) (int, int) {
  74. width, height, _, _ := extractMeta(img, 0, true)
  75. if pages, err := img.GetIntDefault("n-pages", 1); err != nil && pages > 0 {
  76. height /= pages
  77. }
  78. return width, height
  79. }
  80. func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata imagedata.ImageData) error {
  81. if po.Trim.Enabled {
  82. log.Warning("Trim is not supported for animated images")
  83. po.Trim.Enabled = false
  84. }
  85. imgWidth := img.Width()
  86. framesCount := imath.Min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  87. frameHeight, err := img.GetInt("page-height")
  88. if err != nil {
  89. return err
  90. }
  91. // Double check dimensions because animated image has many frames
  92. if err = security.CheckDimensions(imgWidth, frameHeight, framesCount, po.SecurityOptions); err != nil {
  93. return err
  94. }
  95. if img.Pages() > framesCount {
  96. // Load only the needed frames
  97. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  98. return err
  99. }
  100. }
  101. delay, err := img.GetIntSliceDefault("delay", nil)
  102. if err != nil {
  103. return err
  104. }
  105. loop, err := img.GetIntDefault("loop", 0)
  106. if err != nil {
  107. return err
  108. }
  109. watermarkEnabled := po.Watermark.Enabled
  110. po.Watermark.Enabled = false
  111. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  112. frames := make([]*vips.Image, 0, framesCount)
  113. defer func() {
  114. for _, frame := range frames {
  115. if frame != nil {
  116. frame.Clear()
  117. }
  118. }
  119. }()
  120. for i := 0; i < framesCount; i++ {
  121. frame := new(vips.Image)
  122. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  123. return err
  124. }
  125. frames = append(frames, frame)
  126. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  127. return err
  128. }
  129. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  130. if err = frame.CopyMemory(); err != nil {
  131. return err
  132. }
  133. if err = router.CheckTimeout(ctx); err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. if err = img.Arrayjoin(frames); err != nil {
  139. return err
  140. }
  141. if watermarkEnabled && imagedata.Watermark != nil {
  142. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  143. if derr != nil {
  144. dprScale = 1.0
  145. }
  146. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
  147. return err
  148. }
  149. }
  150. if err = img.CastUchar(); err != nil {
  151. return err
  152. }
  153. if len(delay) == 0 {
  154. delay = make([]int, framesCount)
  155. for i := range delay {
  156. delay[i] = 40
  157. }
  158. } else if len(delay) > framesCount {
  159. delay = delay[:framesCount]
  160. }
  161. img.SetInt("imgproxy-is-animated", 1)
  162. img.SetInt("page-height", frames[0].Height())
  163. img.SetIntSlice("delay", delay)
  164. img.SetInt("loop", loop)
  165. img.SetInt("n-pages", img.Height()/frames[0].Height())
  166. return nil
  167. }
  168. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (imagedata.ImageData, error) {
  169. var diff float64
  170. quality := po.GetQuality()
  171. if err := img.CopyMemory(); err != nil {
  172. return nil, err
  173. }
  174. for {
  175. imgdata, err := img.Save(po.Format, quality)
  176. if err != nil {
  177. return nil, err
  178. }
  179. size, err := imgdata.Size()
  180. if err != nil {
  181. return nil, err
  182. }
  183. if size <= po.MaxBytes || quality <= 10 {
  184. return imgdata, err
  185. }
  186. imgdata.Close()
  187. if err := router.CheckTimeout(ctx); err != nil {
  188. return nil, err
  189. }
  190. delta := float64(size) / float64(po.MaxBytes)
  191. switch {
  192. case delta > 3:
  193. diff = 0.25
  194. case delta > 1.5:
  195. diff = 0.5
  196. default:
  197. diff = 0.75
  198. }
  199. quality = int(float64(quality) * diff)
  200. }
  201. }
  202. func ProcessImage(ctx context.Context, imgdata imagedata.ImageData, po *options.ProcessingOptions) (imagedata.ImageData, error) {
  203. runtime.LockOSThread()
  204. defer runtime.UnlockOSThread()
  205. defer vips.Cleanup()
  206. animationSupport :=
  207. po.SecurityOptions.MaxAnimationFrames > 1 &&
  208. imgdata.Format().SupportsAnimationLoad() &&
  209. (po.Format == imagetype.Unknown || po.Format.SupportsAnimationSave())
  210. pages := 1
  211. if animationSupport {
  212. pages = -1
  213. }
  214. img := new(vips.Image)
  215. defer img.Clear()
  216. if po.EnforceThumbnail && imgdata.Format().SupportsThumbnail() {
  217. if err := img.LoadThumbnail(imgdata); err != nil {
  218. log.Debugf("Can't load thumbnail: %s", err)
  219. // Failed to load thumbnail, rollback to the full image
  220. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  221. return nil, err
  222. }
  223. }
  224. } else {
  225. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  226. return nil, err
  227. }
  228. }
  229. originWidth, originHeight := getImageSize(img)
  230. animated := img.IsAnimated()
  231. expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  232. switch {
  233. case po.Format == imagetype.Unknown:
  234. switch {
  235. case po.PreferJxl && !animated:
  236. po.Format = imagetype.JXL
  237. case po.PreferAvif && !animated:
  238. po.Format = imagetype.AVIF
  239. case po.PreferWebP:
  240. po.Format = imagetype.WEBP
  241. case isImageTypePreferred(imgdata.Format()):
  242. po.Format = imgdata.Format()
  243. default:
  244. po.Format = findBestFormat(imgdata.Format(), animated, expectAlpha)
  245. }
  246. case po.EnforceJxl && !animated:
  247. po.Format = imagetype.JXL
  248. case po.EnforceAvif && !animated:
  249. po.Format = imagetype.AVIF
  250. case po.EnforceWebP:
  251. po.Format = imagetype.WEBP
  252. }
  253. if !vips.SupportsSave(po.Format) {
  254. return nil, newSaveFormatError(po.Format)
  255. }
  256. if po.Format.SupportsAnimationSave() && animated {
  257. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  258. return nil, err
  259. }
  260. } else {
  261. if animated {
  262. // We loaded animated image but the resulting format doesn't support
  263. // animations, so we need to reload image as not animated
  264. if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
  265. return nil, err
  266. }
  267. }
  268. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  269. return nil, err
  270. }
  271. }
  272. if err := finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
  273. return nil, err
  274. }
  275. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  276. if img.HasAlpha() {
  277. po.Format = imagetype.PNG
  278. } else {
  279. po.Format = imagetype.JPEG
  280. }
  281. log.Warningf(
  282. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  283. img.Width(), img.Height(), po.Format,
  284. )
  285. }
  286. var (
  287. outData imagedata.ImageData
  288. err error
  289. )
  290. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  291. outData, err = saveImageToFitBytes(ctx, po, img)
  292. } else {
  293. outData, err = img.Save(po.Format, po.GetQuality())
  294. }
  295. if err == nil {
  296. outData.Headers().Set("X-Origin-Width", strconv.Itoa(originWidth))
  297. outData.Headers().Set("X-Origin-Height", strconv.Itoa(originHeight))
  298. outData.Headers().Set("X-Result-Width", strconv.Itoa(img.Width()))
  299. outData.Headers().Set("X-Result-Height", strconv.Itoa(img.Height()))
  300. }
  301. return outData, err
  302. }