processing.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. package processing
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "runtime"
  7. "strconv"
  8. log "github.com/sirupsen/logrus"
  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/imath"
  13. "github.com/imgproxy/imgproxy/v3/options"
  14. "github.com/imgproxy/imgproxy/v3/router"
  15. "github.com/imgproxy/imgproxy/v3/security"
  16. "github.com/imgproxy/imgproxy/v3/vips"
  17. )
  18. var mainPipeline = pipeline{
  19. trim,
  20. prepare,
  21. scaleOnLoad,
  22. importColorProfile,
  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. exportColorProfile,
  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, _, _ := extractMeta(img, 0, true)
  76. if pages, err := img.GetIntDefault("n-pages", 1); err != nil && pages > 0 {
  77. height /= pages
  78. }
  79. return width, height
  80. }
  81. func transformAnimated(ctx context.Context, img *vips.Image, po *options.ProcessingOptions, imgdata *imagedata.ImageData) error {
  82. if po.Trim.Enabled {
  83. log.Warning("Trim is not supported for animated images")
  84. po.Trim.Enabled = false
  85. }
  86. imgWidth := img.Width()
  87. framesCount := imath.Min(img.Pages(), po.SecurityOptions.MaxAnimationFrames)
  88. frameHeight, err := img.GetInt("page-height")
  89. if err != nil {
  90. return err
  91. }
  92. // Double check dimensions because animated image has many frames
  93. if err = security.CheckDimensions(imgWidth, frameHeight, framesCount, po.SecurityOptions); err != nil {
  94. return err
  95. }
  96. if img.Pages() > framesCount {
  97. // Load only the needed frames
  98. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  99. return err
  100. }
  101. }
  102. delay, err := img.GetIntSliceDefault("delay", nil)
  103. if err != nil {
  104. return err
  105. }
  106. loop, err := img.GetIntDefault("loop", 0)
  107. if err != nil {
  108. return err
  109. }
  110. watermarkEnabled := po.Watermark.Enabled
  111. po.Watermark.Enabled = false
  112. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  113. frames := make([]*vips.Image, 0, framesCount)
  114. defer func() {
  115. for _, frame := range frames {
  116. if frame != nil {
  117. frame.Clear()
  118. }
  119. }
  120. }()
  121. for i := 0; i < framesCount; i++ {
  122. frame := new(vips.Image)
  123. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  124. return err
  125. }
  126. frames = append(frames, frame)
  127. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  128. return err
  129. }
  130. if r, _ := frame.GetIntDefault("imgproxy-scaled-down", 0); r == 1 {
  131. if err = frame.CopyMemory(); err != nil {
  132. return err
  133. }
  134. if err = router.CheckTimeout(ctx); err != nil {
  135. return err
  136. }
  137. }
  138. }
  139. if err = img.Arrayjoin(frames); err != nil {
  140. return err
  141. }
  142. if watermarkEnabled && imagedata.Watermark != nil {
  143. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  144. if derr != nil {
  145. dprScale = 1.0
  146. }
  147. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
  148. return err
  149. }
  150. }
  151. if err = img.CastUchar(); err != nil {
  152. return err
  153. }
  154. if len(delay) == 0 {
  155. delay = make([]int, framesCount)
  156. for i := range delay {
  157. delay[i] = 40
  158. }
  159. } else if len(delay) > framesCount {
  160. delay = delay[:framesCount]
  161. }
  162. img.SetInt("imgproxy-is-animated", 1)
  163. img.SetInt("page-height", frames[0].Height())
  164. img.SetIntSlice("delay", delay)
  165. img.SetInt("loop", loop)
  166. img.SetInt("n-pages", img.Height()/frames[0].Height())
  167. return nil
  168. }
  169. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (*imagedata.ImageData, error) {
  170. var diff float64
  171. quality := po.GetQuality()
  172. if err := img.CopyMemory(); err != nil {
  173. return nil, err
  174. }
  175. for {
  176. imgdata, err := img.Save(po.Format, quality)
  177. if err != nil || len(imgdata.Data) <= po.MaxBytes || quality <= 10 {
  178. return imgdata, err
  179. }
  180. imgdata.Close()
  181. if err := router.CheckTimeout(ctx); err != nil {
  182. return nil, err
  183. }
  184. delta := float64(len(imgdata.Data)) / float64(po.MaxBytes)
  185. switch {
  186. case delta > 3:
  187. diff = 0.25
  188. case delta > 1.5:
  189. diff = 0.5
  190. default:
  191. diff = 0.75
  192. }
  193. quality = int(float64(quality) * diff)
  194. }
  195. }
  196. func ProcessImage(ctx context.Context, imgdata *imagedata.ImageData, po *options.ProcessingOptions) (*imagedata.ImageData, error) {
  197. runtime.LockOSThread()
  198. defer runtime.UnlockOSThread()
  199. defer vips.Cleanup()
  200. animationSupport :=
  201. po.SecurityOptions.MaxAnimationFrames > 1 &&
  202. imgdata.Type.SupportsAnimationLoad() &&
  203. (po.Format == imagetype.Unknown || po.Format.SupportsAnimationSave())
  204. pages := 1
  205. if animationSupport {
  206. pages = -1
  207. }
  208. img := new(vips.Image)
  209. defer img.Clear()
  210. if po.EnforceThumbnail && imgdata.Type.SupportsThumbnail() {
  211. if err := img.LoadThumbnail(imgdata); err != nil {
  212. log.Debugf("Can't load thumbnail: %s", err)
  213. // Failed to load thumbnail, rollback to the full image
  214. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  215. return nil, err
  216. }
  217. }
  218. } else {
  219. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  220. return nil, err
  221. }
  222. }
  223. originWidth, originHeight := getImageSize(img)
  224. animated := img.IsAnimated()
  225. expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  226. switch {
  227. case po.Format == imagetype.Unknown:
  228. switch {
  229. case po.PreferJxl && !animated:
  230. po.Format = imagetype.JXL
  231. case po.PreferAvif && !animated:
  232. po.Format = imagetype.AVIF
  233. case po.PreferWebP:
  234. po.Format = imagetype.WEBP
  235. case isImageTypePreferred(imgdata.Type):
  236. po.Format = imgdata.Type
  237. default:
  238. po.Format = findBestFormat(imgdata.Type, animated, expectAlpha)
  239. }
  240. case po.EnforceJxl && !animated:
  241. po.Format = imagetype.JXL
  242. case po.EnforceAvif && !animated:
  243. po.Format = imagetype.AVIF
  244. case po.EnforceWebP:
  245. po.Format = imagetype.WEBP
  246. }
  247. if !vips.SupportsSave(po.Format) {
  248. return nil, fmt.Errorf("Can't save %s, probably not supported by your libvips", po.Format)
  249. }
  250. if po.Format.SupportsAnimationSave() && animated {
  251. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  252. return nil, err
  253. }
  254. } else {
  255. if animated {
  256. // We loaded animated image but the resulting format doesn't support
  257. // animations, so we need to reload image as not animated
  258. if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
  259. return nil, err
  260. }
  261. }
  262. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  263. return nil, err
  264. }
  265. }
  266. if err := finalizePipeline.Run(ctx, img, po, imgdata); err != nil {
  267. return nil, err
  268. }
  269. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  270. if img.HasAlpha() {
  271. po.Format = imagetype.PNG
  272. } else {
  273. po.Format = imagetype.JPEG
  274. }
  275. log.Warningf(
  276. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  277. img.Width(), img.Height(), po.Format,
  278. )
  279. }
  280. var (
  281. outData *imagedata.ImageData
  282. err error
  283. )
  284. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  285. outData, err = saveImageToFitBytes(ctx, po, img)
  286. } else {
  287. outData, err = img.Save(po.Format, po.GetQuality())
  288. }
  289. if err == nil {
  290. if outData.Headers == nil {
  291. outData.Headers = make(map[string]string)
  292. }
  293. outData.Headers["X-Origin-Width"] = strconv.Itoa(originWidth)
  294. outData.Headers["X-Origin-Height"] = strconv.Itoa(originHeight)
  295. outData.Headers["X-Result-Width"] = strconv.Itoa(img.Width())
  296. outData.Headers["X-Result-Height"] = strconv.Itoa(img.Height())
  297. }
  298. return outData, err
  299. }