processing.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. 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.SupportsAnimation() {
  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. frameHeight, err := img.GetInt("page-height")
  86. if err != nil {
  87. return err
  88. }
  89. framesCount := imath.Min(img.Height()/frameHeight, po.SecurityOptions.MaxAnimationFrames)
  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. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  95. if nPages, _ := img.GetIntDefault("n-pages", 1); nPages > framesCount {
  96. // Load only the needed frames
  97. if err = img.Load(imgdata, 1, 1.0, framesCount); err != nil {
  98. return err
  99. }
  100. }
  101. delay, err := img.GetIntSliceDefault("delay", nil)
  102. if err != nil {
  103. return err
  104. }
  105. loop, err := img.GetIntDefault("loop", 0)
  106. if err != nil {
  107. return err
  108. }
  109. watermarkEnabled := po.Watermark.Enabled
  110. po.Watermark.Enabled = false
  111. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  112. frames := make([]*vips.Image, 0, framesCount)
  113. defer func() {
  114. for _, frame := range frames {
  115. if frame != nil {
  116. frame.Clear()
  117. }
  118. }
  119. }()
  120. // Splitting and joining back large WebPs may cause segfault.
  121. // Caching page region cures this
  122. if err = img.LineCache(frameHeight); err != nil {
  123. return err
  124. }
  125. for i := 0; i < framesCount; i++ {
  126. frame := new(vips.Image)
  127. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  128. return err
  129. }
  130. frames = append(frames, frame)
  131. if err = mainPipeline.Run(ctx, frame, po, nil); err != nil {
  132. return err
  133. }
  134. }
  135. if err = img.Arrayjoin(frames); err != nil {
  136. return err
  137. }
  138. if watermarkEnabled && imagedata.Watermark != nil {
  139. dprScale, derr := img.GetDoubleDefault("imgproxy-dpr-scale", 1.0)
  140. if derr != nil {
  141. dprScale = 1.0
  142. }
  143. if err = applyWatermark(img, imagedata.Watermark, &po.Watermark, dprScale, framesCount); err != nil {
  144. return err
  145. }
  146. }
  147. if err = img.CastUchar(); err != nil {
  148. return err
  149. }
  150. if len(delay) == 0 {
  151. delay = make([]int, framesCount)
  152. for i := range delay {
  153. delay[i] = 40
  154. }
  155. } else if len(delay) > framesCount {
  156. delay = delay[:framesCount]
  157. }
  158. img.SetInt("page-height", frames[0].Height())
  159. img.SetIntSlice("delay", delay)
  160. img.SetInt("loop", loop)
  161. img.SetInt("n-pages", framesCount)
  162. return nil
  163. }
  164. func saveImageToFitBytes(ctx context.Context, po *options.ProcessingOptions, img *vips.Image) (*imagedata.ImageData, error) {
  165. var diff float64
  166. quality := po.GetQuality()
  167. if err := img.CopyMemory(); err != nil {
  168. return nil, err
  169. }
  170. for {
  171. imgdata, err := img.Save(po.Format, quality)
  172. if err != nil || len(imgdata.Data) <= po.MaxBytes || quality <= 10 {
  173. return imgdata, err
  174. }
  175. imgdata.Close()
  176. if err := router.CheckTimeout(ctx); err != nil {
  177. return nil, err
  178. }
  179. delta := float64(len(imgdata.Data)) / float64(po.MaxBytes)
  180. switch {
  181. case delta > 3:
  182. diff = 0.25
  183. case delta > 1.5:
  184. diff = 0.5
  185. default:
  186. diff = 0.75
  187. }
  188. quality = int(float64(quality) * diff)
  189. }
  190. }
  191. func ProcessImage(ctx context.Context, imgdata *imagedata.ImageData, po *options.ProcessingOptions) (*imagedata.ImageData, error) {
  192. runtime.LockOSThread()
  193. defer runtime.UnlockOSThread()
  194. defer vips.Cleanup()
  195. animationSupport :=
  196. po.SecurityOptions.MaxAnimationFrames > 1 &&
  197. imgdata.Type.SupportsAnimation() &&
  198. (po.Format == imagetype.Unknown || po.Format.SupportsAnimation())
  199. pages := 1
  200. if animationSupport {
  201. pages = -1
  202. }
  203. img := new(vips.Image)
  204. defer img.Clear()
  205. if po.EnforceThumbnail && imgdata.Type.SupportsThumbnail() {
  206. if err := img.LoadThumbnail(imgdata); err != nil {
  207. log.Debugf("Can't load thumbnail: %s", err)
  208. // Failed to load thumbnail, rollback to the full image
  209. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  210. return nil, err
  211. }
  212. }
  213. } else {
  214. if err := img.Load(imgdata, 1, 1.0, pages); err != nil {
  215. return nil, err
  216. }
  217. }
  218. originWidth, originHeight := getImageSize(img)
  219. animated := img.IsAnimated()
  220. expectAlpha := !po.Flatten && (img.HasAlpha() || po.Padding.Enabled || po.Extend.Enabled)
  221. switch {
  222. case po.Format == imagetype.Unknown:
  223. switch {
  224. case po.PreferAvif && !animated:
  225. po.Format = imagetype.AVIF
  226. case po.PreferWebP:
  227. po.Format = imagetype.WEBP
  228. case isImageTypePreferred(imgdata.Type):
  229. po.Format = imgdata.Type
  230. default:
  231. po.Format = findBestFormat(imgdata.Type, animated, expectAlpha)
  232. }
  233. case po.EnforceAvif && !animated:
  234. po.Format = imagetype.AVIF
  235. case po.EnforceWebP:
  236. po.Format = imagetype.WEBP
  237. }
  238. if !vips.SupportsSave(po.Format) {
  239. return nil, fmt.Errorf("Can't save %s, probably not supported by your libvips", po.Format)
  240. }
  241. if po.Format.SupportsAnimation() && animated {
  242. if err := transformAnimated(ctx, img, po, imgdata); err != nil {
  243. return nil, err
  244. }
  245. } else {
  246. if animated {
  247. // We loaded animated image but the resulting format doesn't support
  248. // animations, so we need to reload image as not animated
  249. if err := img.Load(imgdata, 1, 1.0, 1); err != nil {
  250. return nil, err
  251. }
  252. }
  253. if err := mainPipeline.Run(ctx, img, po, imgdata); err != nil {
  254. return nil, err
  255. }
  256. }
  257. if po.Format == imagetype.AVIF && (img.Width() < 16 || img.Height() < 16) {
  258. if img.HasAlpha() {
  259. po.Format = imagetype.PNG
  260. } else {
  261. po.Format = imagetype.JPEG
  262. }
  263. log.Warningf(
  264. "Minimal dimension of AVIF is 16, current image size is %dx%d. Image will be saved as %s",
  265. img.Width(), img.Height(), po.Format,
  266. )
  267. }
  268. var (
  269. outData *imagedata.ImageData
  270. err error
  271. )
  272. if po.MaxBytes > 0 && po.Format.SupportsQuality() {
  273. outData, err = saveImageToFitBytes(ctx, po, img)
  274. } else {
  275. outData, err = img.Save(po.Format, po.GetQuality())
  276. }
  277. if err == nil {
  278. if outData.Headers == nil {
  279. outData.Headers = make(map[string]string)
  280. }
  281. outData.Headers["X-Origin-Width"] = strconv.Itoa(originWidth)
  282. outData.Headers["X-Origin-Height"] = strconv.Itoa(originHeight)
  283. outData.Headers["X-Result-Width"] = strconv.Itoa(img.Width())
  284. outData.Headers["X-Result-Height"] = strconv.Itoa(img.Height())
  285. }
  286. return outData, err
  287. }