processing.go 15 KB

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