processing.go 8.2 KB

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