process.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. package main
  2. import (
  3. "context"
  4. "math"
  5. "runtime"
  6. "golang.org/x/sync/errgroup"
  7. )
  8. const msgSmartCropNotSupported = "Smart crop is not supported by used version of libvips"
  9. func extractMeta(img *vipsImage) (int, int, int, bool) {
  10. width := img.Width()
  11. height := img.Height()
  12. angle := vipsAngleD0
  13. flip := false
  14. orientation := img.Orientation()
  15. if orientation >= 5 && orientation <= 8 {
  16. width, height = height, width
  17. }
  18. if orientation == 3 || orientation == 4 {
  19. angle = vipsAngleD180
  20. }
  21. if orientation == 5 || orientation == 6 {
  22. angle = vipsAngleD90
  23. }
  24. if orientation == 7 || orientation == 8 {
  25. angle = vipsAngleD270
  26. }
  27. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  28. flip = true
  29. }
  30. return width, height, angle, flip
  31. }
  32. func calcScale(width, height int, po *processingOptions, imgtype imageType) float64 {
  33. var scale float64
  34. srcW, srcH := float64(width), float64(height)
  35. if (po.Width == 0 || po.Width == width) && (po.Height == 0 || po.Height == height) {
  36. scale = 1
  37. } else {
  38. wr := float64(po.Width) / srcW
  39. hr := float64(po.Height) / srcH
  40. if po.Width == 0 {
  41. scale = hr
  42. } else if po.Height == 0 {
  43. scale = wr
  44. } else if po.Resize == resizeFit {
  45. scale = math.Min(wr, hr)
  46. } else {
  47. scale = math.Max(wr, hr)
  48. }
  49. }
  50. scale = scale * po.Dpr
  51. if !po.Enlarge && scale > 1 && imgtype != imageTypeSVG {
  52. return 1
  53. }
  54. if srcW*scale < 1 {
  55. scale = 1 / srcW
  56. }
  57. if srcH*scale < 1 {
  58. scale = 1 / srcH
  59. }
  60. return scale
  61. }
  62. func canScaleOnLoad(imgtype imageType, scale float64) bool {
  63. if imgtype == imageTypeSVG {
  64. return true
  65. }
  66. if conf.DisableShrinkOnLoad || scale >= 1 {
  67. return false
  68. }
  69. return imgtype == imageTypeJPEG || imgtype == imageTypeWEBP
  70. }
  71. func calcJpegShink(scale float64, imgtype imageType) int {
  72. shrink := int(1.0 / scale)
  73. switch {
  74. case shrink >= 8:
  75. return 8
  76. case shrink >= 4:
  77. return 4
  78. case shrink >= 2:
  79. return 2
  80. }
  81. return 1
  82. }
  83. func calcCrop(width, height, cropWidth, cropHeight int, gravity *gravityOptions) (left, top int) {
  84. if gravity.Type == gravityFocusPoint {
  85. pointX := int(float64(width) * gravity.X)
  86. pointY := int(float64(height) * gravity.Y)
  87. left = maxInt(0, minInt(pointX-cropWidth/2, width-cropWidth))
  88. top = maxInt(0, minInt(pointY-cropHeight/2, height-cropHeight))
  89. return
  90. }
  91. left = (width - cropWidth + 1) / 2
  92. top = (height - cropHeight + 1) / 2
  93. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  94. top = 0
  95. }
  96. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  97. left = width - cropWidth
  98. }
  99. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  100. top = height - cropHeight
  101. }
  102. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  103. left = 0
  104. }
  105. return
  106. }
  107. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  108. if cropWidth == 0 && cropHeight == 0 {
  109. return nil
  110. }
  111. imgWidth, imgHeight := img.Width(), img.Height()
  112. if cropWidth == 0 {
  113. cropWidth = imgWidth
  114. } else {
  115. cropWidth = minInt(cropWidth, imgWidth)
  116. }
  117. if cropHeight == 0 {
  118. cropHeight = imgHeight
  119. } else {
  120. cropHeight = minInt(cropHeight, imgHeight)
  121. }
  122. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  123. return nil
  124. }
  125. if gravity.Type == gravitySmart {
  126. if err := img.CopyMemory(); err != nil {
  127. return err
  128. }
  129. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  130. return err
  131. }
  132. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  133. // so we have to copy memory after it
  134. return img.CopyMemory()
  135. }
  136. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  137. return img.Crop(left, top, cropWidth, cropHeight)
  138. }
  139. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  140. var err error
  141. srcWidth, srcHeight, angle, flip := extractMeta(img)
  142. widthToScale, heightToScale := srcWidth, srcHeight
  143. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  144. if cropWidth > 0 {
  145. widthToScale = minInt(cropWidth, srcWidth)
  146. }
  147. if cropHeight > 0 {
  148. heightToScale = minInt(cropHeight, srcHeight)
  149. }
  150. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  151. cropWidth = roundToInt(float64(cropWidth) * scale)
  152. cropHeight = roundToInt(float64(cropHeight) * scale)
  153. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  154. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  155. // Do some scale-on-load
  156. if err := img.Load(data, imgtype, 1, scale, 1); err != nil {
  157. return err
  158. }
  159. } else if imgtype == imageTypeJPEG {
  160. // Do some shrink-on-load
  161. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  162. if err := img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  163. return err
  164. }
  165. }
  166. }
  167. // Update scale after scale-on-load
  168. newWidth, newHeight, _, _ := extractMeta(img)
  169. widthToScale = roundToInt(float64(widthToScale) * float64(newWidth) / float64(srcWidth))
  170. heightToScale = roundToInt(float64(heightToScale) * float64(newHeight) / float64(srcHeight))
  171. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  172. }
  173. if err = img.Rad2Float(); err != nil {
  174. return err
  175. }
  176. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  177. if convertToLinear {
  178. if err = img.ImportColourProfile(true); err != nil {
  179. return err
  180. }
  181. if err = img.LinearColourspace(); err != nil {
  182. return err
  183. }
  184. }
  185. hasAlpha := img.HasAlpha()
  186. if scale != 1 {
  187. if err = img.Resize(scale, hasAlpha); err != nil {
  188. return err
  189. }
  190. }
  191. checkTimeout(ctx)
  192. if angle != vipsAngleD0 || flip {
  193. if err = img.CopyMemory(); err != nil {
  194. return err
  195. }
  196. if angle != vipsAngleD0 {
  197. if err = img.Rotate(angle); err != nil {
  198. return err
  199. }
  200. }
  201. if flip {
  202. if err = img.Flip(); err != nil {
  203. return err
  204. }
  205. }
  206. }
  207. checkTimeout(ctx)
  208. dprWidth := roundToInt(float64(po.Width) * po.Dpr)
  209. dprHeight := roundToInt(float64(po.Height) * po.Dpr)
  210. cropGravity := po.Crop.Gravity
  211. if cropGravity.Type == gravityUnknown {
  212. cropGravity = po.Gravity
  213. }
  214. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  215. if cropWidth == 0 {
  216. cropWidth = dprWidth
  217. } else if dprWidth > 0 {
  218. cropWidth = minInt(cropWidth, dprWidth)
  219. }
  220. if cropHeight == 0 {
  221. cropHeight = dprHeight
  222. } else if dprHeight > 0 {
  223. cropHeight = minInt(cropHeight, dprHeight)
  224. }
  225. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  226. return err
  227. }
  228. } else {
  229. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  230. return err
  231. }
  232. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  233. return err
  234. }
  235. }
  236. checkTimeout(ctx)
  237. if convertToLinear {
  238. if err = img.RgbColourspace(); err != nil {
  239. return err
  240. }
  241. } else {
  242. if err = img.ImportColourProfile(false); err != nil {
  243. return err
  244. }
  245. }
  246. if po.Expand && (po.Width > img.Width() || po.Height > img.Height()) {
  247. if err = img.EnsureAlpha(); err != nil {
  248. return err
  249. }
  250. hasAlpha = true
  251. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0); err != nil {
  252. return err
  253. }
  254. }
  255. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  256. if err = img.Flatten(po.Background); err != nil {
  257. return err
  258. }
  259. }
  260. if po.Blur > 0 {
  261. if err = img.Blur(po.Blur); err != nil {
  262. return err
  263. }
  264. }
  265. if po.Sharpen > 0 {
  266. if err = img.Sharpen(po.Sharpen); err != nil {
  267. return err
  268. }
  269. }
  270. checkTimeout(ctx)
  271. if po.Watermark.Enabled {
  272. if err = img.ApplyWatermark(&po.Watermark); err != nil {
  273. return err
  274. }
  275. }
  276. return img.RgbColourspace()
  277. }
  278. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  279. imgWidth := img.Width()
  280. frameHeight, err := img.GetInt("page-height")
  281. if err != nil {
  282. return err
  283. }
  284. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  285. // Double check dimensions because animated image has many frames
  286. if err := checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  287. return err
  288. }
  289. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  290. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  291. scale := 1.0
  292. // Don't do scale on load if we need to crop
  293. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  294. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  295. }
  296. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  297. logNotice("Animated scale on load")
  298. // Do some scale-on-load and load only the needed frames
  299. if err := img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  300. return err
  301. }
  302. }
  303. imgWidth = img.Width()
  304. frameHeight, err = img.GetInt("page-height")
  305. if err != nil {
  306. return err
  307. }
  308. }
  309. delay, err := img.GetInt("gif-delay")
  310. if err != nil {
  311. return err
  312. }
  313. loop, err := img.GetInt("gif-loop")
  314. if err != nil {
  315. return err
  316. }
  317. frames := make([]*vipsImage, framesCount)
  318. defer func() {
  319. for _, frame := range frames {
  320. frame.Clear()
  321. }
  322. }()
  323. var errg errgroup.Group
  324. for i := 0; i < framesCount; i++ {
  325. ind := i
  326. errg.Go(func() error {
  327. frame := new(vipsImage)
  328. if err := img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  329. return err
  330. }
  331. if err := transformImage(ctx, frame, nil, po, imgtype); err != nil {
  332. return err
  333. }
  334. frames[ind] = frame
  335. return nil
  336. })
  337. }
  338. if err := errg.Wait(); err != nil {
  339. return err
  340. }
  341. checkTimeout(ctx)
  342. if err := img.Arrayjoin(frames); err != nil {
  343. return err
  344. }
  345. img.SetInt("page-height", frames[0].Height())
  346. img.SetInt("gif-delay", delay)
  347. img.SetInt("gif-loop", loop)
  348. img.SetInt("n-pages", framesCount)
  349. return nil
  350. }
  351. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  352. runtime.LockOSThread()
  353. defer runtime.UnlockOSThread()
  354. if newRelicEnabled {
  355. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  356. defer newRelicCancel()
  357. }
  358. if prometheusEnabled {
  359. defer startPrometheusDuration(prometheusProcessingDuration)()
  360. }
  361. defer vipsCleanup()
  362. po := getProcessingOptions(ctx)
  363. data := getImageData(ctx).Bytes()
  364. imgtype := getImageType(ctx)
  365. if po.Format == imageTypeUnknown {
  366. if vipsTypeSupportSave[imgtype] {
  367. po.Format = imgtype
  368. } else {
  369. po.Format = imageTypeJPEG
  370. }
  371. }
  372. if !vipsSupportSmartcrop {
  373. if po.Gravity.Type == gravitySmart {
  374. logWarning(msgSmartCropNotSupported)
  375. po.Gravity.Type = gravityCenter
  376. }
  377. if po.Crop.Gravity.Type == gravitySmart {
  378. logWarning(msgSmartCropNotSupported)
  379. po.Crop.Gravity.Type = gravityCenter
  380. }
  381. }
  382. if po.Resize == resizeCrop {
  383. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  384. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  385. po.Resize = resizeFit
  386. po.Width, po.Height = 0, 0
  387. }
  388. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgtype) && vipsSupportAnimation(po.Format)
  389. pages := 1
  390. if animationSupport {
  391. pages = -1
  392. }
  393. img := new(vipsImage)
  394. defer img.Clear()
  395. if err := img.Load(data, imgtype, 1, 1.0, pages); err != nil {
  396. return nil, func() {}, err
  397. }
  398. if animationSupport && img.IsAnimated() {
  399. if err := transformAnimated(ctx, img, data, po, imgtype); err != nil {
  400. return nil, func() {}, err
  401. }
  402. } else {
  403. if err := transformImage(ctx, img, data, po, imgtype); err != nil {
  404. return nil, func() {}, err
  405. }
  406. }
  407. checkTimeout(ctx)
  408. if po.Format == imageTypeGIF {
  409. if err := img.CastUchar(); err != nil {
  410. return nil, func() {}, err
  411. }
  412. checkTimeout(ctx)
  413. }
  414. return img.Save(po.Format, po.Quality)
  415. }