processing.go 15 KB

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