process.go 14 KB

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