processing.go 15 KB

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