processing.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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/router"
  13. "github.com/imgproxy/imgproxy/v3/security"
  14. "github.com/imgproxy/imgproxy/v3/svg"
  15. "github.com/imgproxy/imgproxy/v3/vips"
  16. )
  17. var mainPipeline = pipeline{
  18. trim,
  19. prepare,
  20. scaleOnLoad,
  21. importColorProfile,
  22. crop,
  23. scale,
  24. rotateAndFlip,
  25. cropToResult,
  26. applyFilters,
  27. extend,
  28. extendAspectRatio,
  29. padding,
  30. fixSize,
  31. flatten,
  32. watermark,
  33. }
  34. var finalizePipeline = pipeline{
  35. exportColorProfile,
  36. stripMetadata,
  37. }
  38. func isImageTypePreferred(imgtype imagetype.Type) bool {
  39. for _, t := range config.PreferredFormats {
  40. if imgtype == t {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. func findBestFormat(srcType imagetype.Type, animated, expectAlpha bool) imagetype.Type {
  47. for _, t := range config.PreferredFormats {
  48. if animated && !t.SupportsAnimationSave() {
  49. continue
  50. }
  51. if expectAlpha && !t.SupportsAlpha() {
  52. continue
  53. }
  54. return t
  55. }
  56. return config.PreferredFormats[0]
  57. }
  58. func ValidatePreferredFormats() error {
  59. filtered := config.PreferredFormats[:0]
  60. for _, t := range config.PreferredFormats {
  61. if !vips.SupportsSave(t) {
  62. log.Warnf("%s can't be a preferred format as it's saving is not supported", t)
  63. } else {
  64. filtered = append(filtered, t)
  65. }
  66. }
  67. if len(filtered) == 0 {
  68. return errors.New("no supported preferred formats specified")
  69. }
  70. config.PreferredFormats = filtered
  71. return nil
  72. }
  73. func getImageSize(img *vips.Image) (int, int) {
  74. width, height, _, _ := extractMeta(img, 0, true)
  75. if pages, err := img.GetIntDefault("n-pages", 1); err != nil && pages > 0 {
  76. height /= pages
  77. }
  78. return width, height
  79. }
  80. func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata imagedata.ImageData) error {
  81. if po.Trim.Enabled {
  82. log.Warning("Trim is not supported for animated images")
  83. po.Trim.Enabled = false
  84. }
  85. imgWidth := img.Width()
  86. framesCount := min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  87. frameHeight, err := img.GetInt("page-height")
  88. if err != nil {
  89. return err
  90. }
  91. // Double check dimensions because animated image has many frames
  92. if err = security.CheckDimensions(imgWidth, frameHeight, framesCount, po.SecurityOptions); err != nil {
  93. return err
  94. }
  95. if img.Pages() > framesCount {
  96. // Load only the needed frames
  97. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  98. return err
  99. }
  100. }
  101. delay, err := img.GetIntSliceDefault("delay", nil)
  102. if err != nil {
  103. return err
  104. }
  105. loop, err := img.GetIntDefault("loop", 0)
  106. if err != nil {
  107. return err
  108. }
  109. watermarkEnabled := po.Watermark.Enabled
  110. po.Watermark.Enabled = false
  111. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  112. frames := make([]*vips.Image, 0, framesCount)
  113. defer func() {
  114. for _, frame := range frames {
  115. if frame != nil {
  116. frame.Clear()
  117. }
  118. }
  119. }()
  120. for i := 0; i < framesCount; i++ {
  121. frame := new(vips.Image)
  122. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  123. return err
  124. }
  125. frames = append(frames, frame)
  126. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  127. return err
  128. }
  129. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  130. if err = frame.CopyMemory(); err != nil {
  131. return err
  132. }
  133. if err = router.CheckTimeout(ctx); err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. if err = img.Arrayjoin(frames); err != nil {
  139. return err
  140. }
  141. if watermarkEnabled && imagedata.Watermark != nil {
  142. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  143. if derr != nil {
  144. dprScale = 1.0
  145. }
  146. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
  147. return err
  148. }
  149. }
  150. if err = img.CastUchar(); err != nil {
  151. return err
  152. }
  153. if len(delay) == 0 {
  154. delay = make([]int, framesCount)
  155. for i := range delay {
  156. delay[i] = 40
  157. }
  158. } else if len(delay) > framesCount {
  159. delay = delay[:framesCount]
  160. }
  161. img.SetInt("imgproxy-is-animated", 1)
  162. img.SetInt("page-height", frames[0].Height())
  163. img.SetIntSlice("delay", delay)
  164. img.SetInt("loop", loop)
  165. img.SetInt("n-pages", img.Height()/frames[0].Height())
  166. return nil
  167. }
  168. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (imagedata.ImageData, error) {
  169. var diff float64
  170. quality := po.GetQuality()
  171. if err := img.CopyMemory(); err != nil {
  172. return nil, err
  173. }
  174. for {
  175. imgdata, err := img.Save(po.Format, quality)
  176. if err != nil {
  177. return nil, err
  178. }
  179. size, err := imgdata.Size()
  180. if err != nil {
  181. return nil, err
  182. }
  183. if size <= po.MaxBytes || quality <= 10 {
  184. return imgdata, err
  185. }
  186. imgdata.Close()
  187. if err := router.CheckTimeout(ctx); err != nil {
  188. return nil, err
  189. }
  190. delta := float64(size) / float64(po.MaxBytes)
  191. switch {
  192. case delta > 3:
  193. diff = 0.25
  194. case delta > 1.5:
  195. diff = 0.5
  196. default:
  197. diff = 0.75
  198. }
  199. quality = int(float64(quality) * diff)
  200. }
  201. }
  202. type Result struct {
  203. OutData imagedata.ImageData
  204. OriginWidth int
  205. OriginHeight int
  206. ResultWidth int
  207. ResultHeight int
  208. }
  209. func ProcessImage(ctx context.Context, imgdata imagedata.ImageData, po *options.ProcessingOptions) (*Result, error) {
  210. runtime.LockOSThread()
  211. defer runtime.UnlockOSThread()
  212. defer vips.Cleanup()
  213. animationSupport :=
  214. po.SecurityOptions.MaxAnimationFrames > 1 &&
  215. imgdata.Format().SupportsAnimationLoad() &&
  216. (po.Format == imagetype.Unknown || po.Format.SupportsAnimationSave())
  217. pages := 1
  218. if animationSupport {
  219. pages = -1
  220. }
  221. img := new(vips.Image)
  222. defer img.Clear()
  223. if po.EnforceThumbnail && imgdata.Format().SupportsThumbnail() {
  224. if err := img.LoadThumbnail(imgdata); err != nil {
  225. log.Debugf("Can't load thumbnail: %s", err)
  226. // Failed to load thumbnail, rollback to the full image
  227. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  228. return nil, err
  229. }
  230. }
  231. } else {
  232. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  233. return nil, err
  234. }
  235. }
  236. originWidth, originHeight := getImageSize(img)
  237. if err := security.CheckDimensions(originWidth, originHeight, 1, po.SecurityOptions); err != nil {
  238. return nil, err
  239. }
  240. // Let's check if we should skip standard processing
  241. if shouldSkipStandardProcessing(imgdata.Format(), po) {
  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. animated := img.IsAnimated()
  266. expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  267. switch {
  268. case po.Format == imagetype.SVG:
  269. // At this point we can't allow requested format to be SVG as we can't save SVGs
  270. return nil, newSaveFormatError(po.Format)
  271. case po.Format == imagetype.Unknown:
  272. switch {
  273. case po.PreferJxl && !animated:
  274. po.Format = imagetype.JXL
  275. case po.PreferAvif && !animated:
  276. po.Format = imagetype.AVIF
  277. case po.PreferWebP:
  278. po.Format = imagetype.WEBP
  279. case isImageTypePreferred(imgdata.Format()):
  280. po.Format = imgdata.Format()
  281. default:
  282. po.Format = findBestFormat(imgdata.Format(), animated, expectAlpha)
  283. }
  284. case po.EnforceJxl && !animated:
  285. po.Format = imagetype.JXL
  286. case po.EnforceAvif && !animated:
  287. po.Format = imagetype.AVIF
  288. case po.EnforceWebP:
  289. po.Format = imagetype.WEBP
  290. }
  291. if !vips.SupportsSave(po.Format) {
  292. return nil, newSaveFormatError(po.Format)
  293. }
  294. if po.Format.SupportsAnimationSave() && animated {
  295. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  296. return nil, err
  297. }
  298. } else {
  299. if animated {
  300. // We loaded animated image but the resulting format doesn't support
  301. // animations, so we need to reload image as not animated
  302. if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
  303. return nil, err
  304. }
  305. }
  306. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  307. return nil, err
  308. }
  309. }
  310. if err := finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
  311. return nil, err
  312. }
  313. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  314. if img.HasAlpha() {
  315. po.Format = imagetype.PNG
  316. } else {
  317. po.Format = imagetype.JPEG
  318. }
  319. log.Warningf(
  320. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  321. img.Width(), img.Height(), po.Format,
  322. )
  323. }
  324. var (
  325. outData imagedata.ImageData
  326. err error
  327. )
  328. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  329. outData, err = saveImageToFitBytes(ctx, po, img)
  330. } else {
  331. outData, err = img.Save(po.Format, po.GetQuality())
  332. }
  333. if err != nil {
  334. return nil, err
  335. }
  336. return &Result{
  337. OutData: outData,
  338. OriginWidth: originWidth,
  339. OriginHeight: originHeight,
  340. ResultWidth: img.Width(),
  341. ResultHeight: img.Height(),
  342. }, nil
  343. }
  344. // Returns true if image should not be processed as usual
  345. func shouldSkipStandardProcessing(inFormat imagetype.Type, po *options.ProcessingOptions) bool {
  346. outFormat := po.Format
  347. skipProcessingInFormatEnabled := slices.Contains(po.SkipProcessingFormats, inFormat)
  348. if inFormat == imagetype.SVG {
  349. isOutUnknown := outFormat == imagetype.Unknown
  350. switch {
  351. case outFormat == imagetype.SVG:
  352. return true
  353. case isOutUnknown && !config.AlwaysRasterizeSvg:
  354. return true
  355. case isOutUnknown && config.AlwaysRasterizeSvg && skipProcessingInFormatEnabled:
  356. return true
  357. default:
  358. return false
  359. }
  360. } else {
  361. return skipProcessingInFormatEnabled && (inFormat == outFormat || outFormat == imagetype.Unknown)
  362. }
  363. }