process.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "math"
  7. "runtime"
  8. imagesize "github.com/imgproxy/imgproxy/image_size"
  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 calcJpegShink(scale float64, imgtype imageType) int {
  107. shrink := int(1.0 / scale)
  108. switch {
  109. case shrink >= 8:
  110. return 8
  111. case shrink >= 4:
  112. return 4
  113. case shrink >= 2:
  114. return 2
  115. }
  116. return 1
  117. }
  118. func calcCrop(width, height, cropWidth, cropHeight int, gravity *gravityOptions) (left, top int) {
  119. if gravity.Type == gravityFocusPoint {
  120. pointX := scaleInt(width, gravity.X)
  121. pointY := scaleInt(height, gravity.Y)
  122. left = maxInt(0, minInt(pointX-cropWidth/2, width-cropWidth))
  123. top = maxInt(0, minInt(pointY-cropHeight/2, height-cropHeight))
  124. return
  125. }
  126. offX, offY := int(gravity.X), int(gravity.Y)
  127. left = (width-cropWidth+1)/2 + offX
  128. top = (height-cropHeight+1)/2 + offY
  129. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  130. top = 0 + offY
  131. }
  132. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  133. left = width - cropWidth - offX
  134. }
  135. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  136. top = height - cropHeight - offY
  137. }
  138. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  139. left = 0 + offX
  140. }
  141. left = maxInt(0, minInt(left, width-cropWidth))
  142. top = maxInt(0, minInt(top, height-cropHeight))
  143. return
  144. }
  145. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  146. if cropWidth == 0 && cropHeight == 0 {
  147. return nil
  148. }
  149. imgWidth, imgHeight := img.Width(), img.Height()
  150. cropWidth = minNonZeroInt(cropWidth, imgWidth)
  151. cropHeight = minNonZeroInt(cropHeight, imgHeight)
  152. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  153. return nil
  154. }
  155. if gravity.Type == gravitySmart {
  156. if err := img.CopyMemory(); err != nil {
  157. return err
  158. }
  159. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  160. return err
  161. }
  162. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  163. // so we have to copy memory after it
  164. return img.CopyMemory()
  165. }
  166. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  167. return img.Crop(left, top, cropWidth, cropHeight)
  168. }
  169. func prepareWatermark(wm *vipsImage, wmData *imageData, opts *watermarkOptions, imgWidth, imgHeight int) error {
  170. if err := wm.Load(wmData.Data, wmData.Type, 1, 1.0, 1); err != nil {
  171. return err
  172. }
  173. po := newProcessingOptions()
  174. po.ResizingType = resizeFit
  175. po.Dpr = 1
  176. po.Enlarge = true
  177. po.Format = wmData.Type
  178. if opts.Scale > 0 {
  179. po.Width = maxInt(scaleInt(imgWidth, opts.Scale), 1)
  180. po.Height = maxInt(scaleInt(imgHeight, opts.Scale), 1)
  181. }
  182. if err := transformImage(context.Background(), wm, wmData.Data, po, wmData.Type); err != nil {
  183. return err
  184. }
  185. if err := wm.EnsureAlpha(); err != nil {
  186. return nil
  187. }
  188. if opts.Replicate {
  189. return wm.Replicate(imgWidth, imgHeight)
  190. }
  191. return wm.Embed(opts.Gravity, imgWidth, imgHeight, opts.OffsetX, opts.OffsetY, rgbColor{0, 0, 0})
  192. }
  193. func applyWatermark(img *vipsImage, wmData *imageData, opts *watermarkOptions, framesCount int) error {
  194. if err := img.RgbColourspace(); err != nil {
  195. return err
  196. }
  197. wm := new(vipsImage)
  198. defer wm.Clear()
  199. width := img.Width()
  200. height := img.Height()
  201. if err := prepareWatermark(wm, wmData, opts, width, height/framesCount); err != nil {
  202. return err
  203. }
  204. if framesCount > 1 {
  205. if err := wm.Replicate(width, height); err != nil {
  206. return err
  207. }
  208. }
  209. opacity := opts.Opacity * conf.WatermarkOpacity
  210. return img.ApplyWatermark(wm, opacity)
  211. }
  212. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  213. var err error
  214. srcWidth, srcHeight, angle, flip := extractMeta(img)
  215. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  216. cropGravity := po.Crop.Gravity
  217. if cropGravity.Type == gravityUnknown {
  218. cropGravity = po.Gravity
  219. }
  220. widthToScale := minNonZeroInt(cropWidth, srcWidth)
  221. heightToScale := minNonZeroInt(cropHeight, srcHeight)
  222. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  223. cropWidth = scaleInt(cropWidth, scale)
  224. cropHeight = scaleInt(cropHeight, scale)
  225. cropGravity.X *= scale
  226. cropGravity.Y *= scale
  227. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  228. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  229. // Do some scale-on-load
  230. if err = img.Load(data, imgtype, 1, scale, 1); err != nil {
  231. return err
  232. }
  233. } else if imgtype == imageTypeJPEG {
  234. // Do some shrink-on-load
  235. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  236. if err = img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  237. return err
  238. }
  239. }
  240. }
  241. // Update scale after scale-on-load
  242. newWidth, newHeight, _, _ := extractMeta(img)
  243. widthToScale = scaleInt(widthToScale, float64(newWidth)/float64(srcWidth))
  244. heightToScale = scaleInt(heightToScale, float64(newHeight)/float64(srcHeight))
  245. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  246. }
  247. if err = img.Rad2Float(); err != nil {
  248. return err
  249. }
  250. iccImported := false
  251. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  252. if convertToLinear || !img.IsSRGB() {
  253. if err = img.ImportColourProfile(true); err != nil {
  254. return err
  255. }
  256. iccImported = true
  257. }
  258. if convertToLinear {
  259. if err = img.LinearColourspace(); err != nil {
  260. return err
  261. }
  262. } else {
  263. if err = img.RgbColourspace(); err != nil {
  264. return err
  265. }
  266. }
  267. hasAlpha := img.HasAlpha()
  268. if scale != 1 {
  269. if err = img.Resize(scale, hasAlpha); err != nil {
  270. return err
  271. }
  272. }
  273. checkTimeout(ctx)
  274. if angle != vipsAngleD0 || flip {
  275. if err = img.CopyMemory(); err != nil {
  276. return err
  277. }
  278. if angle != vipsAngleD0 {
  279. if err = img.Rotate(angle); err != nil {
  280. return err
  281. }
  282. }
  283. if flip {
  284. if err = img.Flip(); err != nil {
  285. return err
  286. }
  287. }
  288. }
  289. checkTimeout(ctx)
  290. dprWidth := scaleInt(po.Width, po.Dpr)
  291. dprHeight := scaleInt(po.Height, po.Dpr)
  292. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  293. cropWidth = minNonZeroInt(cropWidth, dprWidth)
  294. cropHeight = minNonZeroInt(cropHeight, dprHeight)
  295. sumGravity := gravityOptions{
  296. Type: cropGravity.Type,
  297. X: cropGravity.X + po.Gravity.X,
  298. Y: cropGravity.Y + po.Gravity.Y,
  299. }
  300. if err = cropImage(img, cropWidth, cropHeight, &sumGravity); err != nil {
  301. return err
  302. }
  303. } else {
  304. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  305. return err
  306. }
  307. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  308. return err
  309. }
  310. }
  311. checkTimeout(ctx)
  312. if !iccImported {
  313. if err = img.ImportColourProfile(false); err != nil {
  314. return err
  315. }
  316. }
  317. if err = img.RgbColourspace(); err != nil {
  318. return err
  319. }
  320. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  321. if err = img.Flatten(po.Background); err != nil {
  322. return err
  323. }
  324. }
  325. if po.Blur > 0 {
  326. if err = img.Blur(po.Blur); err != nil {
  327. return err
  328. }
  329. }
  330. if po.Sharpen > 0 {
  331. if err = img.Sharpen(po.Sharpen); err != nil {
  332. return err
  333. }
  334. }
  335. if po.Extend && (po.Width > img.Width() || po.Height > img.Height()) {
  336. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0, po.Background); err != nil {
  337. return err
  338. }
  339. }
  340. checkTimeout(ctx)
  341. if po.Watermark.Enabled && watermark != nil {
  342. if err = applyWatermark(img, watermark, &po.Watermark, 1); err != nil {
  343. return err
  344. }
  345. }
  346. return img.RgbColourspace()
  347. }
  348. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  349. imgWidth := img.Width()
  350. frameHeight, err := img.GetInt("page-height")
  351. if err != nil {
  352. return err
  353. }
  354. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  355. // Double check dimensions because animated image has many frames
  356. if err = checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  357. return err
  358. }
  359. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  360. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  361. scale := 1.0
  362. // Don't do scale on load if we need to crop
  363. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  364. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  365. }
  366. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  367. logNotice("Animated scale on load")
  368. // Do some scale-on-load and load only the needed frames
  369. if err = img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  370. return err
  371. }
  372. }
  373. imgWidth = img.Width()
  374. frameHeight, err = img.GetInt("page-height")
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. delay, err := img.GetInt("gif-delay")
  380. if err != nil {
  381. return err
  382. }
  383. loop, err := img.GetInt("gif-loop")
  384. if err != nil {
  385. return err
  386. }
  387. frames := make([]*vipsImage, framesCount)
  388. defer func() {
  389. for _, frame := range frames {
  390. frame.Clear()
  391. }
  392. }()
  393. watermarkEnabled := po.Watermark.Enabled
  394. po.Watermark.Enabled = false
  395. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  396. var errg errgroup.Group
  397. for i := 0; i < framesCount; i++ {
  398. ind := i
  399. errg.Go(func() error {
  400. frame := new(vipsImage)
  401. if err = img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  402. return err
  403. }
  404. if err = transformImage(ctx, frame, nil, po, imgtype); err != nil {
  405. return err
  406. }
  407. frames[ind] = frame
  408. return nil
  409. })
  410. }
  411. if err = errg.Wait(); err != nil {
  412. return err
  413. }
  414. checkTimeout(ctx)
  415. if err = img.Arrayjoin(frames); err != nil {
  416. return err
  417. }
  418. if watermarkEnabled && watermark != nil {
  419. if err = applyWatermark(img, watermark, &po.Watermark, framesCount); err != nil {
  420. return err
  421. }
  422. }
  423. img.SetInt("page-height", frames[0].Height())
  424. img.SetInt("gif-delay", delay)
  425. img.SetInt("gif-loop", loop)
  426. img.SetInt("n-pages", framesCount)
  427. return nil
  428. }
  429. func getIcoData(imgdata *imageData) (*imageData, error) {
  430. offset, size, err := imagesize.BestIcoPage(bytes.NewBuffer(imgdata.Data))
  431. if err != nil {
  432. return nil, err
  433. }
  434. data := imgdata.Data[offset : offset+size]
  435. meta, err := imagesize.DecodeMeta(bytes.NewBuffer(data))
  436. if err != nil {
  437. return nil, err
  438. }
  439. if imgtype, ok := imageTypes[meta.Format]; ok && vipsTypeSupportLoad[imgtype] {
  440. return &imageData{
  441. Data: data,
  442. Type: imgtype,
  443. }, nil
  444. }
  445. return nil, fmt.Errorf("Can't load %s from ICO", meta.Format)
  446. }
  447. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  448. runtime.LockOSThread()
  449. defer runtime.UnlockOSThread()
  450. if newRelicEnabled {
  451. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  452. defer newRelicCancel()
  453. }
  454. if prometheusEnabled {
  455. defer startPrometheusDuration(prometheusProcessingDuration)()
  456. }
  457. defer vipsCleanup()
  458. po := getProcessingOptions(ctx)
  459. imgdata := getImageData(ctx)
  460. if po.Format == imageTypeUnknown {
  461. switch {
  462. case po.PreferWebP && imageTypeSaveSupport(imageTypeWEBP):
  463. po.Format = imageTypeWEBP
  464. case imageTypeSaveSupport(imgdata.Type) && imageTypeGoodForWeb(imgdata.Type):
  465. po.Format = imgdata.Type
  466. default:
  467. po.Format = imageTypeJPEG
  468. }
  469. } else if po.EnforceWebP && imageTypeSaveSupport(imageTypeWEBP) {
  470. po.Format = imageTypeWEBP
  471. }
  472. if po.Format == imageTypeSVG {
  473. if imgdata.Type != imageTypeSVG {
  474. return []byte{}, func() {}, errConvertingNonSvgToSvg
  475. }
  476. return imgdata.Data, func() {}, nil
  477. }
  478. if imgdata.Type == imageTypeSVG && !vipsTypeSupportLoad[imageTypeSVG] {
  479. return []byte{}, func() {}, errSourceImageTypeNotSupported
  480. }
  481. if imgdata.Type == imageTypeICO {
  482. icodata, err := getIcoData(imgdata)
  483. if err != nil {
  484. return nil, func() {}, err
  485. }
  486. imgdata = icodata
  487. }
  488. if !vipsSupportSmartcrop {
  489. if po.Gravity.Type == gravitySmart {
  490. logWarning(msgSmartCropNotSupported)
  491. po.Gravity.Type = gravityCenter
  492. }
  493. if po.Crop.Gravity.Type == gravitySmart {
  494. logWarning(msgSmartCropNotSupported)
  495. po.Crop.Gravity.Type = gravityCenter
  496. }
  497. }
  498. if po.ResizingType == resizeCrop {
  499. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  500. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  501. po.ResizingType = resizeFit
  502. po.Width, po.Height = 0, 0
  503. }
  504. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgdata.Type) && vipsSupportAnimation(po.Format)
  505. pages := 1
  506. if animationSupport {
  507. pages = -1
  508. }
  509. img := new(vipsImage)
  510. defer img.Clear()
  511. if err := img.Load(imgdata.Data, imgdata.Type, 1, 1.0, pages); err != nil {
  512. return nil, func() {}, err
  513. }
  514. if animationSupport && img.IsAnimated() {
  515. if err := transformAnimated(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  516. return nil, func() {}, err
  517. }
  518. } else {
  519. if err := transformImage(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  520. return nil, func() {}, err
  521. }
  522. }
  523. checkTimeout(ctx)
  524. if po.Format == imageTypeGIF {
  525. if err := img.CastUchar(); err != nil {
  526. return nil, func() {}, err
  527. }
  528. checkTimeout(ctx)
  529. }
  530. return img.Save(po.Format, po.Quality)
  531. }