processing.go 15 KB

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