process.go 14 KB

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