process.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. offX, offY := int(gravity.X), int(gravity.Y)
  92. left = (width-cropWidth+1)/2 + offX
  93. top = (height-cropHeight+1)/2 + offY
  94. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  95. top = 0 + offY
  96. }
  97. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  98. left = width - cropWidth - offX
  99. }
  100. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  101. top = height - cropHeight - offY
  102. }
  103. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  104. left = 0 + offX
  105. }
  106. left = maxInt(0, minInt(left, width-cropWidth))
  107. top = maxInt(0, minInt(top, height-cropHeight))
  108. return
  109. }
  110. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  111. if cropWidth == 0 && cropHeight == 0 {
  112. return nil
  113. }
  114. imgWidth, imgHeight := img.Width(), img.Height()
  115. if cropWidth == 0 {
  116. cropWidth = imgWidth
  117. } else {
  118. cropWidth = minInt(cropWidth, imgWidth)
  119. }
  120. if cropHeight == 0 {
  121. cropHeight = imgHeight
  122. } else {
  123. cropHeight = minInt(cropHeight, imgHeight)
  124. }
  125. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  126. return nil
  127. }
  128. if gravity.Type == gravitySmart {
  129. if err := img.CopyMemory(); err != nil {
  130. return err
  131. }
  132. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  133. return err
  134. }
  135. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  136. // so we have to copy memory after it
  137. return img.CopyMemory()
  138. }
  139. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  140. return img.Crop(left, top, cropWidth, cropHeight)
  141. }
  142. func scaleSize(size int, scale float64) int {
  143. if size == 0 {
  144. return 0
  145. }
  146. return roundToInt(float64(size) * scale)
  147. }
  148. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  149. var err error
  150. srcWidth, srcHeight, angle, flip := extractMeta(img)
  151. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  152. cropGravity := po.Crop.Gravity
  153. if cropGravity.Type == gravityUnknown {
  154. cropGravity = po.Gravity
  155. }
  156. widthToScale, heightToScale := srcWidth, srcHeight
  157. if cropWidth > 0 {
  158. widthToScale = minInt(cropWidth, srcWidth)
  159. }
  160. if cropHeight > 0 {
  161. heightToScale = minInt(cropHeight, srcHeight)
  162. }
  163. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  164. cropWidth = scaleSize(cropWidth, scale)
  165. cropHeight = scaleSize(cropHeight, scale)
  166. cropGravity.X = cropGravity.X * scale
  167. cropGravity.Y = cropGravity.Y * scale
  168. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  169. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  170. // Do some scale-on-load
  171. if err := img.Load(data, imgtype, 1, scale, 1); err != nil {
  172. return err
  173. }
  174. } else if imgtype == imageTypeJPEG {
  175. // Do some shrink-on-load
  176. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  177. if err := img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  178. return err
  179. }
  180. }
  181. }
  182. // Update scale after scale-on-load
  183. newWidth, newHeight, _, _ := extractMeta(img)
  184. widthToScale = scaleSize(widthToScale, float64(newWidth)/float64(srcWidth))
  185. heightToScale = scaleSize(heightToScale, float64(newHeight)/float64(srcHeight))
  186. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  187. }
  188. if err = img.Rad2Float(); err != nil {
  189. return err
  190. }
  191. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  192. if convertToLinear {
  193. if err = img.ImportColourProfile(true); err != nil {
  194. return err
  195. }
  196. if err = img.LinearColourspace(); err != nil {
  197. return err
  198. }
  199. }
  200. hasAlpha := img.HasAlpha()
  201. if scale != 1 {
  202. if err = img.Resize(scale, hasAlpha); err != nil {
  203. return err
  204. }
  205. }
  206. checkTimeout(ctx)
  207. if angle != vipsAngleD0 || flip {
  208. if err = img.CopyMemory(); err != nil {
  209. return err
  210. }
  211. if angle != vipsAngleD0 {
  212. if err = img.Rotate(angle); err != nil {
  213. return err
  214. }
  215. }
  216. if flip {
  217. if err = img.Flip(); err != nil {
  218. return err
  219. }
  220. }
  221. }
  222. checkTimeout(ctx)
  223. dprWidth := roundToInt(float64(po.Width) * po.Dpr)
  224. dprHeight := roundToInt(float64(po.Height) * po.Dpr)
  225. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  226. if cropWidth == 0 {
  227. cropWidth = dprWidth
  228. } else if dprWidth > 0 {
  229. cropWidth = minInt(cropWidth, dprWidth)
  230. }
  231. if cropHeight == 0 {
  232. cropHeight = dprHeight
  233. } else if dprHeight > 0 {
  234. cropHeight = minInt(cropHeight, dprHeight)
  235. }
  236. sumGravity := gravityOptions{
  237. Type: cropGravity.Type,
  238. X: cropGravity.X + po.Gravity.X,
  239. Y: cropGravity.Y + po.Gravity.Y,
  240. }
  241. if err = cropImage(img, cropWidth, cropHeight, &sumGravity); err != nil {
  242. return err
  243. }
  244. } else {
  245. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  246. return err
  247. }
  248. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  249. return err
  250. }
  251. }
  252. checkTimeout(ctx)
  253. if convertToLinear {
  254. if err = img.RgbColourspace(); err != nil {
  255. return err
  256. }
  257. } else {
  258. if err = img.ImportColourProfile(false); err != nil {
  259. return err
  260. }
  261. }
  262. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  263. if err = img.Flatten(po.Background); err != nil {
  264. return err
  265. }
  266. }
  267. if po.Blur > 0 {
  268. if err = img.Blur(po.Blur); err != nil {
  269. return err
  270. }
  271. }
  272. if po.Sharpen > 0 {
  273. if err = img.Sharpen(po.Sharpen); err != nil {
  274. return err
  275. }
  276. }
  277. if po.Extend && (po.Width > img.Width() || po.Height > img.Height()) {
  278. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0, po.Background); err != nil {
  279. return err
  280. }
  281. }
  282. checkTimeout(ctx)
  283. if po.Watermark.Enabled {
  284. if err = img.ApplyWatermark(&po.Watermark); err != nil {
  285. return err
  286. }
  287. }
  288. return img.RgbColourspace()
  289. }
  290. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  291. imgWidth := img.Width()
  292. frameHeight, err := img.GetInt("page-height")
  293. if err != nil {
  294. return err
  295. }
  296. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  297. // Double check dimensions because animated image has many frames
  298. if err := checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  299. return err
  300. }
  301. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  302. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  303. scale := 1.0
  304. // Don't do scale on load if we need to crop
  305. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  306. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  307. }
  308. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  309. logNotice("Animated scale on load")
  310. // Do some scale-on-load and load only the needed frames
  311. if err := img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  312. return err
  313. }
  314. }
  315. imgWidth = img.Width()
  316. frameHeight, err = img.GetInt("page-height")
  317. if err != nil {
  318. return err
  319. }
  320. }
  321. delay, err := img.GetInt("gif-delay")
  322. if err != nil {
  323. return err
  324. }
  325. loop, err := img.GetInt("gif-loop")
  326. if err != nil {
  327. return err
  328. }
  329. frames := make([]*vipsImage, framesCount)
  330. defer func() {
  331. for _, frame := range frames {
  332. frame.Clear()
  333. }
  334. }()
  335. var errg errgroup.Group
  336. for i := 0; i < framesCount; i++ {
  337. ind := i
  338. errg.Go(func() error {
  339. frame := new(vipsImage)
  340. if err := img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  341. return err
  342. }
  343. if err := transformImage(ctx, frame, nil, po, imgtype); err != nil {
  344. return err
  345. }
  346. frames[ind] = frame
  347. return nil
  348. })
  349. }
  350. if err := errg.Wait(); err != nil {
  351. return err
  352. }
  353. checkTimeout(ctx)
  354. if err := img.Arrayjoin(frames); err != nil {
  355. return err
  356. }
  357. img.SetInt("page-height", frames[0].Height())
  358. img.SetInt("gif-delay", delay)
  359. img.SetInt("gif-loop", loop)
  360. img.SetInt("n-pages", framesCount)
  361. return nil
  362. }
  363. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  364. runtime.LockOSThread()
  365. defer runtime.UnlockOSThread()
  366. if newRelicEnabled {
  367. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  368. defer newRelicCancel()
  369. }
  370. if prometheusEnabled {
  371. defer startPrometheusDuration(prometheusProcessingDuration)()
  372. }
  373. defer vipsCleanup()
  374. po := getProcessingOptions(ctx)
  375. data := getImageData(ctx).Bytes()
  376. imgtype := getImageType(ctx)
  377. if po.Format == imageTypeUnknown {
  378. if vipsTypeSupportSave[imgtype] {
  379. po.Format = imgtype
  380. } else {
  381. po.Format = imageTypeJPEG
  382. }
  383. }
  384. if !vipsSupportSmartcrop {
  385. if po.Gravity.Type == gravitySmart {
  386. logWarning(msgSmartCropNotSupported)
  387. po.Gravity.Type = gravityCenter
  388. }
  389. if po.Crop.Gravity.Type == gravitySmart {
  390. logWarning(msgSmartCropNotSupported)
  391. po.Crop.Gravity.Type = gravityCenter
  392. }
  393. }
  394. if po.Resize == resizeCrop {
  395. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  396. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  397. po.Resize = resizeFit
  398. po.Width, po.Height = 0, 0
  399. }
  400. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgtype) && vipsSupportAnimation(po.Format)
  401. pages := 1
  402. if animationSupport {
  403. pages = -1
  404. }
  405. img := new(vipsImage)
  406. defer img.Clear()
  407. if err := img.Load(data, imgtype, 1, 1.0, pages); err != nil {
  408. return nil, func() {}, err
  409. }
  410. if animationSupport && img.IsAnimated() {
  411. if err := transformAnimated(ctx, img, data, po, imgtype); err != nil {
  412. return nil, func() {}, err
  413. }
  414. } else {
  415. if err := transformImage(ctx, img, data, po, imgtype); err != nil {
  416. return nil, func() {}, err
  417. }
  418. }
  419. checkTimeout(ctx)
  420. if po.Format == imageTypeGIF {
  421. if err := img.CastUchar(); err != nil {
  422. return nil, func() {}, err
  423. }
  424. checkTimeout(ctx)
  425. }
  426. return img.Save(po.Format, po.Quality)
  427. }