process.go 14 KB

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