processing.go 15 KB

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