process.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 shrink float64
  34. srcW, srcH := float64(width), float64(height)
  35. dstW, dstH := float64(po.Width), float64(po.Height)
  36. if po.Width == 0 {
  37. dstW = srcW
  38. }
  39. if po.Height == 0 {
  40. dstH = srcH
  41. }
  42. if dstW == srcW && dstH == srcH {
  43. shrink = 1
  44. } else {
  45. wshrink := srcW / dstW
  46. hshrink := srcH / dstH
  47. rt := po.Resize
  48. if rt == resizeAuto {
  49. srcD := width - height
  50. dstD := po.Width - po.Height
  51. if (srcD >= 0 && dstD >= 0) || (srcD < 0 && dstD < 0) {
  52. rt = resizeFill
  53. } else {
  54. rt = resizeFit
  55. }
  56. }
  57. switch {
  58. case po.Width == 0:
  59. shrink = hshrink
  60. case po.Height == 0:
  61. shrink = wshrink
  62. case rt == resizeFit:
  63. shrink = math.Max(wshrink, hshrink)
  64. default:
  65. shrink = math.Min(wshrink, hshrink)
  66. }
  67. }
  68. if !po.Enlarge && shrink < 1 && imgtype != imageTypeSVG {
  69. shrink = 1
  70. }
  71. shrink /= po.Dpr
  72. if shrink > srcW {
  73. shrink = srcW
  74. }
  75. if shrink > srcH {
  76. shrink = srcH
  77. }
  78. return 1.0 / shrink
  79. }
  80. func canScaleOnLoad(imgtype imageType, scale float64) bool {
  81. if imgtype == imageTypeSVG {
  82. return true
  83. }
  84. if conf.DisableShrinkOnLoad || scale >= 1 {
  85. return false
  86. }
  87. return imgtype == imageTypeJPEG || imgtype == imageTypeWEBP
  88. }
  89. func calcJpegShink(scale float64, imgtype imageType) int {
  90. shrink := int(1.0 / scale)
  91. switch {
  92. case shrink >= 8:
  93. return 8
  94. case shrink >= 4:
  95. return 4
  96. case shrink >= 2:
  97. return 2
  98. }
  99. return 1
  100. }
  101. func calcCrop(width, height, cropWidth, cropHeight int, gravity *gravityOptions) (left, top int) {
  102. if gravity.Type == gravityFocusPoint {
  103. pointX := scaleInt(width, gravity.X)
  104. pointY := scaleInt(height, gravity.Y)
  105. left = maxInt(0, minInt(pointX-cropWidth/2, width-cropWidth))
  106. top = maxInt(0, minInt(pointY-cropHeight/2, height-cropHeight))
  107. return
  108. }
  109. offX, offY := int(gravity.X), int(gravity.Y)
  110. left = (width-cropWidth+1)/2 + offX
  111. top = (height-cropHeight+1)/2 + offY
  112. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  113. top = 0 + offY
  114. }
  115. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  116. left = width - cropWidth - offX
  117. }
  118. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  119. top = height - cropHeight - offY
  120. }
  121. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  122. left = 0 + offX
  123. }
  124. left = maxInt(0, minInt(left, width-cropWidth))
  125. top = maxInt(0, minInt(top, height-cropHeight))
  126. return
  127. }
  128. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  129. if cropWidth == 0 && cropHeight == 0 {
  130. return nil
  131. }
  132. imgWidth, imgHeight := img.Width(), img.Height()
  133. cropWidth = minNonZeroInt(cropWidth, imgWidth)
  134. cropHeight = minNonZeroInt(cropHeight, imgHeight)
  135. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  136. return nil
  137. }
  138. if gravity.Type == gravitySmart {
  139. if err := img.CopyMemory(); err != nil {
  140. return err
  141. }
  142. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  143. return err
  144. }
  145. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  146. // so we have to copy memory after it
  147. return img.CopyMemory()
  148. }
  149. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  150. return img.Crop(left, top, cropWidth, cropHeight)
  151. }
  152. func prepareWatermark(wm *vipsImage, wmData *imageData, opts *watermarkOptions, imgWidth, imgHeight int) error {
  153. if err := wm.Load(wmData.Data, wmData.Type, 1, 1.0, 1); err != nil {
  154. return err
  155. }
  156. po := newProcessingOptions()
  157. po.Resize = resizeFit
  158. po.Dpr = 1
  159. po.Enlarge = true
  160. po.Format = wmData.Type
  161. if opts.Scale > 0 {
  162. po.Width = maxInt(scaleInt(imgWidth, opts.Scale), 1)
  163. po.Height = maxInt(scaleInt(imgHeight, opts.Scale), 1)
  164. }
  165. if err := transformImage(context.Background(), wm, wmData.Data, po, wmData.Type); err != nil {
  166. return err
  167. }
  168. if err := wm.EnsureAlpha(); err != nil {
  169. return nil
  170. }
  171. if opts.Replicate {
  172. return wm.Replicate(imgWidth, imgHeight)
  173. }
  174. return wm.Embed(opts.Gravity, imgWidth, imgHeight, opts.OffsetX, opts.OffsetY, rgbColor{0, 0, 0})
  175. }
  176. func applyWatermark(img *vipsImage, wmData *imageData, opts *watermarkOptions, framesCount int) error {
  177. wm := new(vipsImage)
  178. defer wm.Clear()
  179. width := img.Width()
  180. height := img.Height()
  181. if err := prepareWatermark(wm, wmData, opts, width, height/framesCount); err != nil {
  182. return err
  183. }
  184. if framesCount > 1 {
  185. if err := wm.Replicate(width, height); err != nil {
  186. return err
  187. }
  188. }
  189. opacity := opts.Opacity * conf.WatermarkOpacity
  190. return img.ApplyWatermark(wm, opacity)
  191. }
  192. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  193. var err error
  194. srcWidth, srcHeight, angle, flip := extractMeta(img)
  195. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  196. cropGravity := po.Crop.Gravity
  197. if cropGravity.Type == gravityUnknown {
  198. cropGravity = po.Gravity
  199. }
  200. widthToScale := minNonZeroInt(cropWidth, srcWidth)
  201. heightToScale := minNonZeroInt(cropHeight, srcHeight)
  202. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  203. cropWidth = scaleInt(cropWidth, scale)
  204. cropHeight = scaleInt(cropHeight, scale)
  205. cropGravity.X *= scale
  206. cropGravity.Y *= scale
  207. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  208. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  209. // Do some scale-on-load
  210. if err = img.Load(data, imgtype, 1, scale, 1); err != nil {
  211. return err
  212. }
  213. } else if imgtype == imageTypeJPEG {
  214. // Do some shrink-on-load
  215. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  216. if err = img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  217. return err
  218. }
  219. }
  220. }
  221. // Update scale after scale-on-load
  222. newWidth, newHeight, _, _ := extractMeta(img)
  223. widthToScale = scaleInt(widthToScale, float64(newWidth)/float64(srcWidth))
  224. heightToScale = scaleInt(heightToScale, float64(newHeight)/float64(srcHeight))
  225. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  226. }
  227. if err = img.Rad2Float(); err != nil {
  228. return err
  229. }
  230. iccImported := false
  231. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  232. if convertToLinear || !img.IsSRGB() {
  233. if err = img.ImportColourProfile(true); err != nil {
  234. return err
  235. }
  236. iccImported = true
  237. }
  238. if convertToLinear {
  239. if err = img.LinearColourspace(); err != nil {
  240. return err
  241. }
  242. } else {
  243. if err = img.RgbColourspace(); err != nil {
  244. return err
  245. }
  246. }
  247. hasAlpha := img.HasAlpha()
  248. if scale != 1 {
  249. if err = img.Resize(scale, hasAlpha); err != nil {
  250. return err
  251. }
  252. }
  253. checkTimeout(ctx)
  254. if angle != vipsAngleD0 || flip {
  255. if err = img.CopyMemory(); err != nil {
  256. return err
  257. }
  258. if angle != vipsAngleD0 {
  259. if err = img.Rotate(angle); err != nil {
  260. return err
  261. }
  262. }
  263. if flip {
  264. if err = img.Flip(); err != nil {
  265. return err
  266. }
  267. }
  268. }
  269. checkTimeout(ctx)
  270. dprWidth := scaleInt(po.Width, po.Dpr)
  271. dprHeight := scaleInt(po.Height, po.Dpr)
  272. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  273. cropWidth = minNonZeroInt(cropWidth, dprWidth)
  274. cropHeight = minNonZeroInt(cropHeight, dprHeight)
  275. sumGravity := gravityOptions{
  276. Type: cropGravity.Type,
  277. X: cropGravity.X + po.Gravity.X,
  278. Y: cropGravity.Y + po.Gravity.Y,
  279. }
  280. if err = cropImage(img, cropWidth, cropHeight, &sumGravity); err != nil {
  281. return err
  282. }
  283. } else {
  284. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  285. return err
  286. }
  287. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  288. return err
  289. }
  290. }
  291. checkTimeout(ctx)
  292. if !iccImported {
  293. if err = img.ImportColourProfile(false); err != nil {
  294. return err
  295. }
  296. }
  297. if err = img.RgbColourspace(); err != nil {
  298. return err
  299. }
  300. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  301. if err = img.Flatten(po.Background); err != nil {
  302. return err
  303. }
  304. }
  305. if po.Blur > 0 {
  306. if err = img.Blur(po.Blur); err != nil {
  307. return err
  308. }
  309. }
  310. if po.Sharpen > 0 {
  311. if err = img.Sharpen(po.Sharpen); err != nil {
  312. return err
  313. }
  314. }
  315. if po.Extend && (po.Width > img.Width() || po.Height > img.Height()) {
  316. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0, po.Background); err != nil {
  317. return err
  318. }
  319. }
  320. checkTimeout(ctx)
  321. if po.Watermark.Enabled && watermark != nil {
  322. if err = applyWatermark(img, watermark, &po.Watermark, 1); err != nil {
  323. return err
  324. }
  325. }
  326. return img.RgbColourspace()
  327. }
  328. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  329. imgWidth := img.Width()
  330. frameHeight, err := img.GetInt("page-height")
  331. if err != nil {
  332. return err
  333. }
  334. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  335. // Double check dimensions because animated image has many frames
  336. if err = checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  337. return err
  338. }
  339. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  340. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  341. scale := 1.0
  342. // Don't do scale on load if we need to crop
  343. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  344. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  345. }
  346. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  347. logNotice("Animated scale on load")
  348. // Do some scale-on-load and load only the needed frames
  349. if err = img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  350. return err
  351. }
  352. }
  353. imgWidth = img.Width()
  354. frameHeight, err = img.GetInt("page-height")
  355. if err != nil {
  356. return err
  357. }
  358. }
  359. delay, err := img.GetInt("gif-delay")
  360. if err != nil {
  361. return err
  362. }
  363. loop, err := img.GetInt("gif-loop")
  364. if err != nil {
  365. return err
  366. }
  367. frames := make([]*vipsImage, framesCount)
  368. defer func() {
  369. for _, frame := range frames {
  370. frame.Clear()
  371. }
  372. }()
  373. watermarkEnabled := po.Watermark.Enabled
  374. po.Watermark.Enabled = false
  375. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  376. var errg errgroup.Group
  377. for i := 0; i < framesCount; i++ {
  378. ind := i
  379. errg.Go(func() error {
  380. frame := new(vipsImage)
  381. if err = img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  382. return err
  383. }
  384. if err = transformImage(ctx, frame, nil, po, imgtype); err != nil {
  385. return err
  386. }
  387. frames[ind] = frame
  388. return nil
  389. })
  390. }
  391. if err = errg.Wait(); err != nil {
  392. return err
  393. }
  394. checkTimeout(ctx)
  395. if err = img.Arrayjoin(frames); err != nil {
  396. return err
  397. }
  398. if watermarkEnabled && watermark != nil {
  399. if err = applyWatermark(img, watermark, &po.Watermark, framesCount); err != nil {
  400. return err
  401. }
  402. }
  403. img.SetInt("page-height", frames[0].Height())
  404. img.SetInt("gif-delay", delay)
  405. img.SetInt("gif-loop", loop)
  406. img.SetInt("n-pages", framesCount)
  407. return nil
  408. }
  409. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  410. runtime.LockOSThread()
  411. defer runtime.UnlockOSThread()
  412. if newRelicEnabled {
  413. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  414. defer newRelicCancel()
  415. }
  416. if prometheusEnabled {
  417. defer startPrometheusDuration(prometheusProcessingDuration)()
  418. }
  419. defer vipsCleanup()
  420. po := getProcessingOptions(ctx)
  421. imgdata := getImageData(ctx)
  422. if po.Format == imageTypeUnknown {
  423. switch {
  424. case po.PreferWebP && vipsTypeSupportSave[imageTypeWEBP]:
  425. po.Format = imageTypeWEBP
  426. case vipsTypeSupportSave[imgdata.Type] && imgdata.Type != imageTypeHEIC && imgdata.Type != imageTypeTIFF:
  427. po.Format = imgdata.Type
  428. default:
  429. po.Format = imageTypeJPEG
  430. }
  431. } else if po.EnforceWebP && vipsTypeSupportSave[imageTypeWEBP] {
  432. po.Format = imageTypeWEBP
  433. }
  434. if !vipsSupportSmartcrop {
  435. if po.Gravity.Type == gravitySmart {
  436. logWarning(msgSmartCropNotSupported)
  437. po.Gravity.Type = gravityCenter
  438. }
  439. if po.Crop.Gravity.Type == gravitySmart {
  440. logWarning(msgSmartCropNotSupported)
  441. po.Crop.Gravity.Type = gravityCenter
  442. }
  443. }
  444. if po.Resize == resizeCrop {
  445. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  446. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  447. po.Resize = resizeFit
  448. po.Width, po.Height = 0, 0
  449. }
  450. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgdata.Type) && vipsSupportAnimation(po.Format)
  451. pages := 1
  452. if animationSupport {
  453. pages = -1
  454. }
  455. img := new(vipsImage)
  456. defer img.Clear()
  457. if err := img.Load(imgdata.Data, imgdata.Type, 1, 1.0, pages); err != nil {
  458. return nil, func() {}, err
  459. }
  460. if animationSupport && img.IsAnimated() {
  461. if err := transformAnimated(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  462. return nil, func() {}, err
  463. }
  464. } else {
  465. if err := transformImage(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  466. return nil, func() {}, err
  467. }
  468. }
  469. checkTimeout(ctx)
  470. if po.Format == imageTypeGIF {
  471. if err := img.CastUchar(); err != nil {
  472. return nil, func() {}, err
  473. }
  474. checkTimeout(ctx)
  475. }
  476. return img.Save(po.Format, po.Quality)
  477. }