processing.go 15 KB

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