process.go 17 KB

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