processing.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package processing
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "runtime"
  7. "slices"
  8. "github.com/imgproxy/imgproxy/v3/auximageprovider"
  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/security"
  13. "github.com/imgproxy/imgproxy/v3/server"
  14. "github.com/imgproxy/imgproxy/v3/svg"
  15. "github.com/imgproxy/imgproxy/v3/vips"
  16. )
  17. // mainPipeline constructs the main image processing pipeline.
  18. // This pipeline is applied to each image frame.
  19. func (p *Processor) mainPipeline() Pipeline {
  20. return Pipeline{
  21. p.vectorGuardScale,
  22. p.trim,
  23. p.scaleOnLoad,
  24. p.colorspaceToProcessing,
  25. p.crop,
  26. p.scale,
  27. p.rotateAndFlip,
  28. p.cropToResult,
  29. p.applyFilters,
  30. p.extend,
  31. p.extendAspectRatio,
  32. p.padding,
  33. p.fixSize,
  34. p.flatten,
  35. p.watermark,
  36. }
  37. }
  38. // finalizePipeline constructs the finalization pipeline.
  39. // This pipeline is applied before saving the image.
  40. func (p *Processor) finalizePipeline() Pipeline {
  41. return Pipeline{
  42. p.colorspaceToResult,
  43. p.stripMetadata,
  44. }
  45. }
  46. // Result holds the result of image processing.
  47. type Result struct {
  48. OutData imagedata.ImageData
  49. OriginWidth int
  50. OriginHeight int
  51. ResultWidth int
  52. ResultHeight int
  53. }
  54. // ProcessImage processes the image according to the provided processing options
  55. // and returns a [Result] that includes the processed image data and dimensions.
  56. //
  57. // The provided processing options may be modified during processing.
  58. func (p *Processor) ProcessImage(
  59. ctx context.Context,
  60. imgdata imagedata.ImageData,
  61. po *options.ProcessingOptions,
  62. watermarkProvider auximageprovider.Provider,
  63. ) (*Result, error) {
  64. runtime.LockOSThread()
  65. defer runtime.UnlockOSThread()
  66. defer vips.Cleanup()
  67. img := new(vips.Image)
  68. defer img.Clear()
  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)
  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 := po.SecurityOptions.MaxAnimationFrames > 1 &&
  83. img.IsAnimated()
  84. // Determine output format and check if it's supported.
  85. // The determined format is stored in po.Format.
  86. if err = p.determineOutputFormat(img, imgdata, po, animated); 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 && po.Format.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, 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(), po.SecurityOptions)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Transform the image (resize, crop, etc)
  106. if err = p.transformImage(ctx, img, po, 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, 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, 1.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 *options.ProcessingOptions,
  149. asAnimated bool,
  150. ) error {
  151. // If we are going to process the image as animated, we need to load all frames
  152. // up to MaxAnimationFrames
  153. if asAnimated {
  154. frames := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  155. return img.Load(imgdata, 1, 1.0, frames)
  156. }
  157. // Otherwise, we just need to remove any animation-related data
  158. return img.RemoveAnimation()
  159. }
  160. // checkImageSize checks the image dimensions and number of frames against security options.
  161. // It returns the image width, height and a security check error, if any.
  162. func (p *Processor) checkImageSize(
  163. img *vips.Image,
  164. imgtype imagetype.Type,
  165. secops security.Options,
  166. ) (int, int, error) {
  167. width, height, frames := p.getImageSize(img)
  168. if imgtype.IsVector() {
  169. // We don't check vector image dimensions as we can render it in any size
  170. return width, height, nil
  171. }
  172. err := secops.CheckDimensions(width, height, frames)
  173. return width, height, err
  174. }
  175. // getImageSize returns the width and height of the image, taking into account
  176. // orientation and animation.
  177. func (p *Processor) getImageSize(img *vips.Image) (int, int, int) {
  178. width, height := img.Width(), img.Height()
  179. frames := 1
  180. if img.IsAnimated() {
  181. // Animated images contain multiple frames, and libvips loads them stacked vertically.
  182. // We want to return the size of a single frame
  183. height = img.PageHeight()
  184. frames = img.PagesLoaded()
  185. }
  186. // If the image is rotated by 90 or 270 degrees, we need to swap width and height
  187. orientation := img.Orientation()
  188. if orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8 {
  189. width, height = height, width
  190. }
  191. return width, height, frames
  192. }
  193. // Returns true if image should not be processed as usual
  194. func (p *Processor) shouldSkipStandardProcessing(
  195. inFormat imagetype.Type,
  196. po *options.ProcessingOptions,
  197. ) bool {
  198. outFormat := po.Format
  199. skipProcessingFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
  200. if inFormat == imagetype.SVG {
  201. isOutUnknown := outFormat == imagetype.Unknown
  202. switch {
  203. case outFormat == imagetype.SVG:
  204. return true
  205. case isOutUnknown && !p.config.AlwaysRasterizeSvg:
  206. return true
  207. case isOutUnknown && p.config.AlwaysRasterizeSvg && skipProcessingFormatEnabled:
  208. return true
  209. default:
  210. return false
  211. }
  212. } else {
  213. return skipProcessingFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
  214. }
  215. }
  216. // skipStandardProcessing skips standard image processing and returns the original image data.
  217. //
  218. // SVG images may be sanitized if configured to do so.
  219. func (p *Processor) skipStandardProcessing(
  220. img *vips.Image,
  221. imgdata imagedata.ImageData,
  222. po *options.ProcessingOptions,
  223. ) (*Result, error) {
  224. // Even if we skip standard processing, we still need to check image dimensions
  225. // to not send an image bomb to the client
  226. originWidth, originHeight, err := p.checkImageSize(img, imgdata.Format(), po.SecurityOptions)
  227. if err != nil {
  228. return nil, err
  229. }
  230. // Even in this case, SVG is an exception
  231. if imgdata.Format() == imagetype.SVG && p.config.SanitizeSvg {
  232. sanitized, err := svg.Sanitize(imgdata)
  233. if err != nil {
  234. return nil, err
  235. }
  236. return &Result{
  237. OutData: sanitized,
  238. OriginWidth: originWidth,
  239. OriginHeight: originHeight,
  240. ResultWidth: originWidth,
  241. ResultHeight: originHeight,
  242. }, nil
  243. }
  244. // Return the original image
  245. return &Result{
  246. OutData: imgdata,
  247. OriginWidth: originWidth,
  248. OriginHeight: originHeight,
  249. ResultWidth: originWidth,
  250. ResultHeight: originHeight,
  251. }, nil
  252. }
  253. // determineOutputFormat determines the output image format based on the processing options
  254. // and image properties.
  255. //
  256. // It modifies the ProcessingOptions in place to set the output format.
  257. func (p *Processor) determineOutputFormat(
  258. img *vips.Image,
  259. imgdata imagedata.ImageData,
  260. po *options.ProcessingOptions,
  261. animated bool,
  262. ) error {
  263. // Check if the image may have transparency
  264. expectTransparency := !po.Flatten &&
  265. (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  266. switch {
  267. case po.Format == imagetype.SVG:
  268. // At this point we can't allow requested format to be SVG as we can't save SVGs
  269. return newSaveFormatError(po.Format)
  270. case po.Format == imagetype.Unknown:
  271. switch {
  272. case po.PreferJxl && !animated:
  273. po.Format = imagetype.JXL
  274. case po.PreferAvif && !animated:
  275. po.Format = imagetype.AVIF
  276. case po.PreferWebP:
  277. po.Format = imagetype.WEBP
  278. case p.isImageTypePreferred(imgdata.Format()):
  279. po.Format = imgdata.Format()
  280. default:
  281. po.Format = p.findPreferredFormat(animated, expectTransparency)
  282. }
  283. case po.EnforceJxl && !animated:
  284. po.Format = imagetype.JXL
  285. case po.EnforceAvif && !animated:
  286. po.Format = imagetype.AVIF
  287. case po.EnforceWebP:
  288. po.Format = imagetype.WEBP
  289. }
  290. if !vips.SupportsSave(po.Format) {
  291. return newSaveFormatError(po.Format)
  292. }
  293. return nil
  294. }
  295. // isImageTypePreferred checks if the given image type is in the list of preferred formats.
  296. func (p *Processor) isImageTypePreferred(imgtype imagetype.Type) bool {
  297. return slices.Contains(p.config.PreferredFormats, imgtype)
  298. }
  299. // isImageTypeCompatible checks if the given image type is compatible with the image properties.
  300. func (p *Processor) isImageTypeCompatible(
  301. imgtype imagetype.Type,
  302. animated, expectTransparency bool,
  303. ) bool {
  304. if animated && !imgtype.SupportsAnimationSave() {
  305. return false
  306. }
  307. if expectTransparency && !imgtype.SupportsAlpha() {
  308. return false
  309. }
  310. return true
  311. }
  312. // findPreferredFormat finds a suitable preferred format based on image's properties.
  313. func (p *Processor) findPreferredFormat(animated, expectTransparency bool) imagetype.Type {
  314. for _, t := range p.config.PreferredFormats {
  315. if p.isImageTypeCompatible(t, animated, expectTransparency) {
  316. return t
  317. }
  318. }
  319. return p.config.PreferredFormats[0]
  320. }
  321. func (p *Processor) transformImage(
  322. ctx context.Context,
  323. img *vips.Image,
  324. po *options.ProcessingOptions,
  325. imgdata imagedata.ImageData,
  326. asAnimated bool,
  327. ) error {
  328. if asAnimated {
  329. return p.transformAnimated(ctx, img, po)
  330. }
  331. return p.mainPipeline().Run(ctx, img, po, imgdata)
  332. }
  333. func (p *Processor) transformAnimated(
  334. ctx context.Context,
  335. img *vips.Image,
  336. po *options.ProcessingOptions,
  337. ) error {
  338. if po.Trim.Enabled {
  339. slog.Warn("Trim is not supported for animated images")
  340. po.Trim.Enabled = false
  341. }
  342. imgWidth := img.Width()
  343. frameHeight := img.PageHeight()
  344. framesCount := img.PagesLoaded()
  345. // Get frame delays. We'll need to set them back later.
  346. // If we don't have delay info, we'll set a default delay later.
  347. delay, err := img.GetIntSliceDefault("delay", nil)
  348. if err != nil {
  349. return err
  350. }
  351. // Get loop count. We'll need to set it back later.
  352. // 0 means infinite looping.
  353. loop, err := img.GetIntDefault("loop", 0)
  354. if err != nil {
  355. return err
  356. }
  357. // Disable watermarking for individual frames.
  358. // It's more efficient to apply watermark to all frames at once after they are processed.
  359. watermarkEnabled := po.Watermark.Enabled
  360. po.Watermark.Enabled = false
  361. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  362. // Make a slice to hold processed frames and ensure they are cleared on function exit
  363. frames := make([]*vips.Image, 0, framesCount)
  364. defer func() {
  365. for _, frame := range frames {
  366. if frame != nil {
  367. frame.Clear()
  368. }
  369. }
  370. }()
  371. for i := 0; i < framesCount; i++ {
  372. frame := new(vips.Image)
  373. // Extract an individual frame from the image.
  374. // Libvips loads animated images as a single image with frames stacked vertically.
  375. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  376. return err
  377. }
  378. frames = append(frames, frame)
  379. // Transform the frame using the main pipeline.
  380. // We don't provide imgdata here to prevent scale-on-load.
  381. // Watermarking is disabled for individual frames (see above)
  382. if err = p.mainPipeline().Run(ctx, frame, po, nil); err != nil {
  383. return err
  384. }
  385. // If the frame was scaled down, it's better to copy it to RAM
  386. // to speed up further processing.
  387. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  388. if err = frame.CopyMemory(); err != nil {
  389. return err
  390. }
  391. if err = server.CheckTimeout(ctx); err != nil {
  392. return err
  393. }
  394. }
  395. }
  396. // Join processed frames back into a single image.
  397. if err = img.Arrayjoin(frames); err != nil {
  398. return err
  399. }
  400. // Apply watermark to all frames at once if it was requested.
  401. // This is much more efficient than applying watermark to individual frames.
  402. if watermarkEnabled && p.watermarkProvider != nil {
  403. // Get DPR scale to apply watermark correctly on HiDPI images.
  404. // `imgproxy-dpr-scale` is set by the pipeline.
  405. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  406. if derr != nil {
  407. dprScale = 1.0
  408. }
  409. if err = p.applyWatermark(ctx, img, po, 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 *options.ProcessingOptions,
  436. ) (imagedata.ImageData, error) {
  437. // AVIF has a minimal dimension of 16 pixels.
  438. // If one of the dimensions is less, we need to switch to another format.
  439. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  440. if img.HasAlpha() {
  441. po.Format = imagetype.PNG
  442. } else {
  443. po.Format = imagetype.JPEG
  444. }
  445. slog.Warn(fmt.Sprintf(
  446. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  447. img.Width(), img.Height(), po.Format,
  448. ))
  449. }
  450. // If we want and can fit the image into the specified number of bytes,
  451. // let's do it.
  452. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  453. return saveImageToFitBytes(ctx, po, img)
  454. }
  455. // Otherwise, just save the image with the specified quality.
  456. return img.Save(po.Format, po.GetQuality())
  457. }