processing.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package processing
  2. import (
  3. "context"
  4. "errors"
  5. "runtime"
  6. "slices"
  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/options"
  12. "github.com/imgproxy/imgproxy/v3/router"
  13. "github.com/imgproxy/imgproxy/v3/security"
  14. "github.com/imgproxy/imgproxy/v3/svg"
  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 := img.Width(), img.Height()
  75. if img.IsAnimated() {
  76. // Animated images contain multiple frames, and libvips loads them stacked vertically.
  77. // We want to return the size of a single frame
  78. height = img.PageHeight()
  79. }
  80. // If the image is rotated by 90 or 270 degrees, we need to swap width and height
  81. orientation := img.Orientation()
  82. if orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8 {
  83. width, height = height, width
  84. }
  85. return width, height
  86. }
  87. func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata imagedata.ImageData) error {
  88. if po.Trim.Enabled {
  89. log.Warning("Trim is not supported for animated images")
  90. po.Trim.Enabled = false
  91. }
  92. imgWidth := img.Width()
  93. framesCount := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  94. frameHeight, err := img.GetInt("page-height")
  95. if err != nil {
  96. return err
  97. }
  98. // Double check dimensions because animated image has many frames
  99. if err = security.CheckDimensions(imgWidth, frameHeight, framesCount, po.SecurityOptions); err != nil {
  100. return err
  101. }
  102. if img.Pages() > framesCount {
  103. // Load only the needed frames
  104. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  105. return err
  106. }
  107. }
  108. delay, err := img.GetIntSliceDefault("delay", nil)
  109. if err != nil {
  110. return err
  111. }
  112. loop, err := img.GetIntDefault("loop", 0)
  113. if err != nil {
  114. return err
  115. }
  116. watermarkEnabled := po.Watermark.Enabled
  117. po.Watermark.Enabled = false
  118. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  119. frames := make([]*vips.Image, 0, framesCount)
  120. defer func() {
  121. for _, frame := range frames {
  122. if frame != nil {
  123. frame.Clear()
  124. }
  125. }
  126. }()
  127. for i := 0; i < framesCount; i++ {
  128. frame := new(vips.Image)
  129. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  130. return err
  131. }
  132. frames = append(frames, frame)
  133. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  134. return err
  135. }
  136. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  137. if err = frame.CopyMemory(); err != nil {
  138. return err
  139. }
  140. if err = router.CheckTimeout(ctx); err != nil {
  141. return err
  142. }
  143. }
  144. }
  145. if err = img.Arrayjoin(frames); err != nil {
  146. return err
  147. }
  148. if watermarkEnabled && imagedata.Watermark != nil {
  149. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  150. if derr != nil {
  151. dprScale = 1.0
  152. }
  153. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
  154. return err
  155. }
  156. }
  157. if err = img.CastUchar(); err != nil {
  158. return err
  159. }
  160. if len(delay) == 0 {
  161. delay = make([]int, framesCount)
  162. for i := range delay {
  163. delay[i] = 40
  164. }
  165. } else if len(delay) > framesCount {
  166. delay = delay[:framesCount]
  167. }
  168. img.SetInt("imgproxy-is-animated", 1)
  169. img.SetInt("page-height", frames[0].Height())
  170. img.SetIntSlice("delay", delay)
  171. img.SetInt("loop", loop)
  172. img.SetInt("n-pages", img.Height()/frames[0].Height())
  173. return nil
  174. }
  175. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (imagedata.ImageData, error) {
  176. var diff float64
  177. quality := po.GetQuality()
  178. if err := img.CopyMemory(); err != nil {
  179. return nil, err
  180. }
  181. for {
  182. imgdata, err := img.Save(po.Format, quality)
  183. if err != nil {
  184. return nil, err
  185. }
  186. size, err := imgdata.Size()
  187. if err != nil {
  188. return nil, err
  189. }
  190. if size <= po.MaxBytes || quality <= 10 {
  191. return imgdata, err
  192. }
  193. imgdata.Close()
  194. if err := router.CheckTimeout(ctx); err != nil {
  195. return nil, err
  196. }
  197. delta := float64(size) / float64(po.MaxBytes)
  198. switch {
  199. case delta > 3:
  200. diff = 0.25
  201. case delta > 1.5:
  202. diff = 0.5
  203. default:
  204. diff = 0.75
  205. }
  206. quality = int(float64(quality) * diff)
  207. }
  208. }
  209. type Result struct {
  210. OutData imagedata.ImageData
  211. OriginWidth int
  212. OriginHeight int
  213. ResultWidth int
  214. ResultHeight int
  215. }
  216. func ProcessImage(ctx context.Context, imgdata imagedata.ImageData, po *options.ProcessingOptions) (*Result, error) {
  217. runtime.LockOSThread()
  218. defer runtime.UnlockOSThread()
  219. defer vips.Cleanup()
  220. animationSupport :=
  221. po.SecurityOptions.MaxAnimationFrames > 1 &&
  222. imgdata.Format().SupportsAnimationLoad() &&
  223. (po.Format == imagetype.Unknown || po.Format.SupportsAnimationSave())
  224. pages := 1
  225. if animationSupport {
  226. pages = -1
  227. }
  228. img := new(vips.Image)
  229. defer img.Clear()
  230. if po.EnforceThumbnail && imgdata.Format().SupportsThumbnail() {
  231. if err := img.LoadThumbnail(imgdata); err != nil {
  232. log.Debugf("Can't load thumbnail: %s", err)
  233. // Failed to load thumbnail, rollback to the full image
  234. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  235. return nil, err
  236. }
  237. }
  238. } else {
  239. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  240. return nil, err
  241. }
  242. }
  243. originWidth, originHeight := getImageSize(img)
  244. if err := security.CheckDimensions(originWidth, originHeight, 1, po.SecurityOptions); err != nil {
  245. return nil, err
  246. }
  247. // Let's check if we should skip standard processing
  248. if shouldSkipStandardProcessing(imgdata.Format(), po) {
  249. // Even in this case, SVG is an exception
  250. if imgdata.Format() == imagetype.SVG && config.SanitizeSvg {
  251. sanitized, err := svg.Sanitize(imgdata)
  252. if err != nil {
  253. return nil, err
  254. }
  255. return &Result{
  256. OutData: sanitized,
  257. OriginWidth: originWidth,
  258. OriginHeight: originHeight,
  259. ResultWidth: originWidth,
  260. ResultHeight: originHeight,
  261. }, nil
  262. }
  263. // Return the original image
  264. return &Result{
  265. OutData: imgdata,
  266. OriginWidth: originWidth,
  267. OriginHeight: originHeight,
  268. ResultWidth: originWidth,
  269. ResultHeight: originHeight,
  270. }, nil
  271. }
  272. animated := img.IsAnimated()
  273. expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  274. switch {
  275. case po.Format == imagetype.SVG:
  276. // At this point we can't allow requested format to be SVG as we can't save SVGs
  277. return nil, newSaveFormatError(po.Format)
  278. case po.Format == imagetype.Unknown:
  279. switch {
  280. case po.PreferJxl && !animated:
  281. po.Format = imagetype.JXL
  282. case po.PreferAvif && !animated:
  283. po.Format = imagetype.AVIF
  284. case po.PreferWebP:
  285. po.Format = imagetype.WEBP
  286. case isImageTypePreferred(imgdata.Format()):
  287. po.Format = imgdata.Format()
  288. default:
  289. po.Format = findBestFormat(imgdata.Format(), animated, expectAlpha)
  290. }
  291. case po.EnforceJxl && !animated:
  292. po.Format = imagetype.JXL
  293. case po.EnforceAvif && !animated:
  294. po.Format = imagetype.AVIF
  295. case po.EnforceWebP:
  296. po.Format = imagetype.WEBP
  297. }
  298. if !vips.SupportsSave(po.Format) {
  299. return nil, newSaveFormatError(po.Format)
  300. }
  301. if po.Format.SupportsAnimationSave() && animated {
  302. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  303. return nil, err
  304. }
  305. } else {
  306. if animated {
  307. // We loaded animated image but the resulting format doesn't support
  308. // animations, so we need to reload image as not animated
  309. if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
  310. return nil, err
  311. }
  312. }
  313. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  314. return nil, err
  315. }
  316. }
  317. if err := finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
  318. return nil, err
  319. }
  320. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  321. if img.HasAlpha() {
  322. po.Format = imagetype.PNG
  323. } else {
  324. po.Format = imagetype.JPEG
  325. }
  326. log.Warningf(
  327. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  328. img.Width(), img.Height(), po.Format,
  329. )
  330. }
  331. var (
  332. outData imagedata.ImageData
  333. err error
  334. )
  335. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  336. outData, err = saveImageToFitBytes(ctx, po, img)
  337. } else {
  338. outData, err = img.Save(po.Format, po.GetQuality())
  339. }
  340. if err != nil {
  341. return nil, err
  342. }
  343. resultWidth, resultHeight := getImageSize(img)
  344. return &Result{
  345. OutData: outData,
  346. OriginWidth: originWidth,
  347. OriginHeight: originHeight,
  348. ResultWidth: resultWidth,
  349. ResultHeight: resultHeight,
  350. }, nil
  351. }
  352. // Returns true if image should not be processed as usual
  353. func shouldSkipStandardProcessing(inFormat imagetype.Type, po *options.ProcessingOptions) bool {
  354. outFormat := po.Format
  355. skipProcessingInFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
  356. if inFormat == imagetype.SVG {
  357. isOutUnknown := outFormat == imagetype.Unknown
  358. switch {
  359. case outFormat == imagetype.SVG:
  360. return true
  361. case isOutUnknown && !config.AlwaysRasterizeSvg:
  362. return true
  363. case isOutUnknown && config.AlwaysRasterizeSvg && skipProcessingInFormatEnabled:
  364. return true
  365. default:
  366. return false
  367. }
  368. } else {
  369. return skipProcessingInFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
  370. }
  371. }