processing.go 8.4 KB

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