processing.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package processing
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "runtime"
  7. "slices"
  8. "github.com/imgproxy/imgproxy/v3/imagedata"
  9. "github.com/imgproxy/imgproxy/v3/imagetype"
  10. "github.com/imgproxy/imgproxy/v3/options"
  11. "github.com/imgproxy/imgproxy/v3/security"
  12. "github.com/imgproxy/imgproxy/v3/server"
  13. "github.com/imgproxy/imgproxy/v3/vips"
  14. )
  15. // mainPipeline constructs the main image processing pipeline.
  16. // This pipeline is applied to each image frame.
  17. func (p *Processor) mainPipeline() Pipeline {
  18. return Pipeline{
  19. p.vectorGuardScale,
  20. p.trim,
  21. p.scaleOnLoad,
  22. p.colorspaceToProcessing,
  23. p.crop,
  24. p.scale,
  25. p.rotateAndFlip,
  26. p.cropToResult,
  27. p.applyFilters,
  28. p.extend,
  29. p.extendAspectRatio,
  30. p.padding,
  31. p.fixSize,
  32. p.flatten,
  33. p.watermark,
  34. }
  35. }
  36. // finalizePipeline constructs the finalization pipeline.
  37. // This pipeline is applied before saving the image.
  38. func (p *Processor) finalizePipeline() Pipeline {
  39. return Pipeline{
  40. p.colorspaceToResult,
  41. p.stripMetadata,
  42. }
  43. }
  44. // Result holds the result of image processing.
  45. type Result struct {
  46. OutData imagedata.ImageData
  47. OriginWidth int
  48. OriginHeight int
  49. ResultWidth int
  50. ResultHeight int
  51. }
  52. // ProcessImage processes the image according to the provided processing options
  53. // and returns a [Result] that includes the processed image data and dimensions.
  54. //
  55. // The provided processing options may be modified during processing.
  56. func (p *Processor) ProcessImage(
  57. ctx context.Context,
  58. imgdata imagedata.ImageData,
  59. o *options.Options,
  60. secops security.Options,
  61. ) (*Result, error) {
  62. runtime.LockOSThread()
  63. defer runtime.UnlockOSThread()
  64. defer vips.Cleanup()
  65. img := new(vips.Image)
  66. defer img.Clear()
  67. po := p.NewProcessingOptions(o)
  68. // Load a single page/frame of the image so we can analyze it
  69. // and decide how to process it further
  70. thumbnailLoaded, err := p.initialLoadImage(img, imgdata, po.EnforceThumbnail())
  71. if err != nil {
  72. return nil, err
  73. }
  74. // Let's check if we should skip standard processing
  75. if p.shouldSkipStandardProcessing(imgdata.Format(), po) {
  76. return p.skipStandardProcessing(img, imgdata, po, secops)
  77. }
  78. // Check if we expect image to be processed as animated.
  79. // If MaxAnimationFrames is 1, we never process as animated since we can only
  80. // process a single frame.
  81. animated := secops.MaxAnimationFrames > 1 &&
  82. img.IsAnimated()
  83. // Determine output format and check if it's supported.
  84. // The determined format is stored in po[KeyFormat].
  85. outFormat, err := p.determineOutputFormat(img, imgdata, po, animated)
  86. if err != nil {
  87. return nil, err
  88. }
  89. // Now, as we know the output format, we know for sure if the image
  90. // should be processed as animated
  91. animated = animated && outFormat.SupportsAnimationSave()
  92. // Load required number of frames/pages for processing
  93. // and remove animation-related data if not animated.
  94. // Don't reload if we initially loaded a thumbnail.
  95. if !thumbnailLoaded {
  96. if err = p.reloadImageForProcessing(img, imgdata, po, secops, animated); err != nil {
  97. return nil, err
  98. }
  99. }
  100. // Check image dimensions and number of frames for security reasons
  101. originWidth, originHeight, err := p.checkImageSize(img, imgdata.Format(), secops)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Transform the image (resize, crop, etc)
  106. if err = p.transformImage(ctx, img, po, secops, imgdata, animated); err != nil {
  107. return nil, err
  108. }
  109. // Finalize the image (colorspace conversion, metadata stripping, etc)
  110. if err = p.finalizePipeline().Run(ctx, img, po, secops, imgdata); err != nil {
  111. return nil, err
  112. }
  113. outData, err := p.saveImage(ctx, img, po)
  114. if err != nil {
  115. return nil, err
  116. }
  117. resultWidth, resultHeight, _ := p.getImageSize(img)
  118. return &Result{
  119. OutData: outData,
  120. OriginWidth: originWidth,
  121. OriginHeight: originHeight,
  122. ResultWidth: resultWidth,
  123. ResultHeight: resultHeight,
  124. }, nil
  125. }
  126. // initialLoadImage loads a single page/frame of the image.
  127. // If the image format supports thumbnails and thumbnail loading is enforced,
  128. // it tries to load the thumbnail first.
  129. func (p *Processor) initialLoadImage(
  130. img *vips.Image,
  131. imgdata imagedata.ImageData,
  132. enforceThumbnail bool,
  133. ) (bool, error) {
  134. if enforceThumbnail && imgdata.Format().SupportsThumbnail() {
  135. if err := img.LoadThumbnail(imgdata); err == nil {
  136. return true, nil
  137. } else {
  138. slog.Debug(fmt.Sprintf("Can't load thumbnail: %s", err))
  139. }
  140. }
  141. return false, img.Load(imgdata, 1.0, 0, 1)
  142. }
  143. // reloadImageForProcessing reloads the image for processing.
  144. // For animated images, it loads all frames up to MaxAnimationFrames.
  145. func (p *Processor) reloadImageForProcessing(
  146. img *vips.Image,
  147. imgdata imagedata.ImageData,
  148. po ProcessingOptions,
  149. secops security.Options,
  150. asAnimated bool,
  151. ) error {
  152. // If we are going to process the image as animated, we need to load all frames
  153. // up to MaxAnimationFrames
  154. if asAnimated {
  155. frames := min(img.Pages(), secops.MaxAnimationFrames)
  156. return img.Load(imgdata, 1.0, 0, frames)
  157. }
  158. // Otherwise, we just need to remove any animation-related data
  159. return img.RemoveAnimation()
  160. }
  161. // checkImageSize checks the image dimensions and number of frames against security options.
  162. // It returns the image width, height and a security check error, if any.
  163. func (p *Processor) checkImageSize(
  164. img *vips.Image,
  165. imgtype imagetype.Type,
  166. secops security.Options,
  167. ) (int, int, error) {
  168. width, height, frames := p.getImageSize(img)
  169. if imgtype.IsVector() {
  170. // We don't check vector image dimensions as we can render it in any size
  171. return width, height, nil
  172. }
  173. err := secops.CheckDimensions(width, height, frames)
  174. return width, height, err
  175. }
  176. // getImageSize returns the width and height of the image, taking into account
  177. // orientation and animation.
  178. func (p *Processor) getImageSize(img *vips.Image) (int, int, int) {
  179. width, height := img.Width(), img.Height()
  180. frames := 1
  181. if img.IsAnimated() {
  182. // Animated images contain multiple frames, and libvips loads them stacked vertically.
  183. // We want to return the size of a single frame
  184. height = img.PageHeight()
  185. frames = img.PagesLoaded()
  186. }
  187. // If the image is rotated by 90 or 270 degrees, we need to swap width and height
  188. orientation := img.Orientation()
  189. if orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8 {
  190. width, height = height, width
  191. }
  192. return width, height, frames
  193. }
  194. // Returns true if image should not be processed as usual
  195. func (p *Processor) shouldSkipStandardProcessing(
  196. inFormat imagetype.Type,
  197. po ProcessingOptions,
  198. ) bool {
  199. outFormat := po.Format()
  200. skipProcessingFormatEnabled := po.ShouldSkipFormatProcessing(inFormat)
  201. if inFormat == imagetype.SVG {
  202. isOutUnknown := outFormat == imagetype.Unknown
  203. switch {
  204. case outFormat == imagetype.SVG:
  205. return true
  206. case isOutUnknown && !p.config.AlwaysRasterizeSvg:
  207. return true
  208. case isOutUnknown && p.config.AlwaysRasterizeSvg && skipProcessingFormatEnabled:
  209. return true
  210. default:
  211. return false
  212. }
  213. } else {
  214. return skipProcessingFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
  215. }
  216. }
  217. // skipStandardProcessing skips standard image processing and returns the original image data.
  218. //
  219. // SVG images may be sanitized if configured to do so.
  220. func (p *Processor) skipStandardProcessing(
  221. img *vips.Image,
  222. imgdata imagedata.ImageData,
  223. po ProcessingOptions,
  224. secops security.Options,
  225. ) (*Result, error) {
  226. // Even if we skip standard processing, we still need to check image dimensions
  227. // to not send an image bomb to the client
  228. originWidth, originHeight, err := p.checkImageSize(img, imgdata.Format(), secops)
  229. if err != nil {
  230. return nil, err
  231. }
  232. imgdata, err = p.svg.Process(po.Options, imgdata)
  233. if err != nil {
  234. return nil, err
  235. }
  236. // Return the original image
  237. return &Result{
  238. OutData: imgdata,
  239. OriginWidth: originWidth,
  240. OriginHeight: originHeight,
  241. ResultWidth: originWidth,
  242. ResultHeight: originHeight,
  243. }, nil
  244. }
  245. // determineOutputFormat determines the output image format based on the processing options
  246. // and image properties.
  247. //
  248. // It modifies the ProcessingOptions in place to set the output format.
  249. func (p *Processor) determineOutputFormat(
  250. img *vips.Image,
  251. imgdata imagedata.ImageData,
  252. po ProcessingOptions,
  253. animated bool,
  254. ) (imagetype.Type, error) {
  255. // Check if the image may have transparency
  256. expectTransparency := !po.ShouldFlatten() &&
  257. (img.HasAlpha() || po.PaddingEnabled() || po.ExtendEnabled())
  258. format := po.Format()
  259. switch {
  260. case format == imagetype.SVG:
  261. // At this point we can't allow requested format to be SVG as we can't save SVGs
  262. return imagetype.Unknown, newSaveFormatError(format)
  263. case format == imagetype.Unknown:
  264. switch {
  265. case po.PreferJxl() && !animated:
  266. format = imagetype.JXL
  267. case po.PreferAvif() && !animated:
  268. format = imagetype.AVIF
  269. case po.PreferWebP():
  270. format = imagetype.WEBP
  271. case p.isImageTypePreferred(imgdata.Format()):
  272. format = imgdata.Format()
  273. default:
  274. format = p.findPreferredFormat(animated, expectTransparency)
  275. }
  276. case po.EnforceJxl() && !animated:
  277. format = imagetype.JXL
  278. case po.EnforceAvif() && !animated:
  279. format = imagetype.AVIF
  280. case po.EnforceWebP():
  281. format = imagetype.WEBP
  282. }
  283. po.SetFormat(format)
  284. if !vips.SupportsSave(format) {
  285. return format, newSaveFormatError(format)
  286. }
  287. return format, nil
  288. }
  289. // isImageTypePreferred checks if the given image type is in the list of preferred formats.
  290. func (p *Processor) isImageTypePreferred(imgtype imagetype.Type) bool {
  291. return slices.Contains(p.config.PreferredFormats, imgtype)
  292. }
  293. // isImageTypeCompatible checks if the given image type is compatible with the image properties.
  294. func (p *Processor) isImageTypeCompatible(
  295. imgtype imagetype.Type,
  296. animated, expectTransparency bool,
  297. ) bool {
  298. if animated && !imgtype.SupportsAnimationSave() {
  299. return false
  300. }
  301. if expectTransparency && !imgtype.SupportsAlpha() {
  302. return false
  303. }
  304. return true
  305. }
  306. // findPreferredFormat finds a suitable preferred format based on image's properties.
  307. func (p *Processor) findPreferredFormat(animated, expectTransparency bool) imagetype.Type {
  308. for _, t := range p.config.PreferredFormats {
  309. if p.isImageTypeCompatible(t, animated, expectTransparency) {
  310. return t
  311. }
  312. }
  313. return p.config.PreferredFormats[0]
  314. }
  315. func (p *Processor) transformImage(
  316. ctx context.Context,
  317. img *vips.Image,
  318. po ProcessingOptions,
  319. secops security.Options,
  320. imgdata imagedata.ImageData,
  321. asAnimated bool,
  322. ) error {
  323. if asAnimated {
  324. return p.transformAnimated(ctx, img, po, secops)
  325. }
  326. return p.mainPipeline().Run(ctx, img, po, secops, imgdata)
  327. }
  328. func (p *Processor) transformAnimated(
  329. ctx context.Context,
  330. img *vips.Image,
  331. po ProcessingOptions,
  332. secops security.Options,
  333. ) error {
  334. if po.TrimEnabled() {
  335. slog.Warn("Trim is not supported for animated images")
  336. po.DisableTrim()
  337. }
  338. imgWidth := img.Width()
  339. frameHeight := img.PageHeight()
  340. framesCount := img.PagesLoaded()
  341. // Get frame delays. We'll need to set them back later.
  342. // If we don't have delay info, we'll set a default delay later.
  343. delay, err := img.GetIntSliceDefault("delay", nil)
  344. if err != nil {
  345. return err
  346. }
  347. // Get loop count. We'll need to set it back later.
  348. // 0 means infinite looping.
  349. loop, err := img.GetIntDefault("loop", 0)
  350. if err != nil {
  351. return err
  352. }
  353. // Disable watermarking for individual frames.
  354. // It's more efficient to apply watermark to all frames at once after they are processed.
  355. watermarkOpacity := po.WatermarkOpacity()
  356. if watermarkOpacity > 0 {
  357. po.DeleteWatermarkOpacity()
  358. defer func() { po.SetWatermarkOpacity(watermarkOpacity) }()
  359. }
  360. // Make a slice to hold processed frames and ensure they are cleared on function exit
  361. frames := make([]*vips.Image, 0, framesCount)
  362. defer func() {
  363. for _, frame := range frames {
  364. if frame != nil {
  365. frame.Clear()
  366. }
  367. }
  368. }()
  369. for i := 0; i < framesCount; i++ {
  370. frame := new(vips.Image)
  371. // Extract an individual frame from the image.
  372. // Libvips loads animated images as a single image with frames stacked vertically.
  373. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  374. return err
  375. }
  376. frames = append(frames, frame)
  377. // Transform the frame using the main pipeline.
  378. // We don't provide imgdata here to prevent scale-on-load.
  379. // Watermarking is disabled for individual frames (see above)
  380. if err = p.mainPipeline().Run(ctx, frame, po, secops, nil); err != nil {
  381. return err
  382. }
  383. // If the frame was scaled down, it's better to copy it to RAM
  384. // to speed up further processing.
  385. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  386. if err = frame.CopyMemory(); err != nil {
  387. return err
  388. }
  389. if err = server.CheckTimeout(ctx); err != nil {
  390. return err
  391. }
  392. }
  393. }
  394. // Join processed frames back into a single image.
  395. if err = img.Arrayjoin(frames); err != nil {
  396. return err
  397. }
  398. // Apply watermark to all frames at once if it was requested.
  399. // This is much more efficient than applying watermark to individual frames.
  400. if watermarkOpacity > 0 && p.watermarkProvider != nil {
  401. // Get DPR scale to apply watermark correctly on HiDPI images.
  402. // `imgproxy-dpr-scale` is set by the pipeline.
  403. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  404. if derr != nil {
  405. dprScale = 1.0
  406. }
  407. // Set watermark opacity back
  408. po.SetWatermarkOpacity(watermarkOpacity)
  409. if err = p.applyWatermark(ctx, img, po, secops, dprScale, framesCount); err != nil {
  410. return err
  411. }
  412. }
  413. if len(delay) == 0 {
  414. // if we don't have delay info, set it to 40ms for each frame (25 FPS).
  415. delay = make([]int, framesCount)
  416. for i := range delay {
  417. delay[i] = 40
  418. }
  419. } else if len(delay) > framesCount {
  420. // if we have more delay entries than frames, truncate it.
  421. delay = delay[:framesCount]
  422. }
  423. // Mark the image as animated so img.Strip() doesn't remove animation data.
  424. img.SetInt("imgproxy-is-animated", 1)
  425. // Set animation data back.
  426. img.SetInt("page-height", frames[0].Height())
  427. img.SetIntSlice("delay", delay)
  428. img.SetInt("loop", loop)
  429. img.SetInt("n-pages", img.Height()/frames[0].Height())
  430. return nil
  431. }
  432. func (p *Processor) saveImage(
  433. ctx context.Context,
  434. img *vips.Image,
  435. po ProcessingOptions,
  436. ) (imagedata.ImageData, error) {
  437. outFormat := po.Format()
  438. // AVIF has a minimal dimension of 16 pixels.
  439. // If one of the dimensions is less, we need to switch to another format.
  440. if outFormat == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  441. if img.HasAlpha() {
  442. outFormat = imagetype.PNG
  443. } else {
  444. outFormat = imagetype.JPEG
  445. }
  446. po.SetFormat(outFormat)
  447. slog.Warn(fmt.Sprintf(
  448. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  449. img.Width(), img.Height(), outFormat,
  450. ))
  451. }
  452. quality := po.Quality(outFormat)
  453. // If we want and can fit the image into the specified number of bytes,
  454. // let's do it.
  455. if maxBytes := po.MaxBytes(); maxBytes > 0 && outFormat.SupportsQuality() {
  456. return saveImageToFitBytes(ctx, img, outFormat, quality, maxBytes, po.Options)
  457. }
  458. // Otherwise, just save the image with the specified quality.
  459. return img.Save(outFormat, quality, po.Options)
  460. }