processing.go 10 KB

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