processing.go 8.2 KB

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