process.go 15 KB

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