processing.go 16 KB

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