process.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "math"
  7. "runtime"
  8. "github.com/imgproxy/imgproxy/v2/imagemeta"
  9. )
  10. const (
  11. // https://chromium.googlesource.com/webm/libwebp/+/refs/heads/master/src/webp/encode.h#529
  12. webpMaxDimension = 16383.0
  13. )
  14. var errConvertingNonSvgToSvg = newError(422, "Converting non-SVG images to SVG is not supported", "Converting non-SVG images to SVG is not supported")
  15. func imageTypeLoadSupport(imgtype imageType) bool {
  16. return imgtype == imageTypeSVG ||
  17. imgtype == imageTypeICO ||
  18. vipsTypeSupportLoad[imgtype]
  19. }
  20. func imageTypeSaveSupport(imgtype imageType) bool {
  21. return imgtype == imageTypeSVG || vipsTypeSupportSave[imgtype]
  22. }
  23. func imageTypeGoodForWeb(imgtype imageType) bool {
  24. return imgtype != imageTypeTIFF &&
  25. imgtype != imageTypeBMP
  26. }
  27. func canSwitchFormat(src, dst, want imageType) bool {
  28. return imageTypeSaveSupport(want) &&
  29. (!vipsSupportAnimation(src) ||
  30. (dst != imageTypeUnknown && !vipsSupportAnimation(dst)) ||
  31. vipsSupportAnimation(want))
  32. }
  33. func extractMeta(img *vipsImage, baseAngle int, useOrientation bool) (int, int, int, bool) {
  34. width := img.Width()
  35. height := img.Height()
  36. angle := 0
  37. flip := false
  38. if useOrientation {
  39. orientation := img.Orientation()
  40. if orientation == 3 || orientation == 4 {
  41. angle = 180
  42. }
  43. if orientation == 5 || orientation == 6 {
  44. angle = 90
  45. }
  46. if orientation == 7 || orientation == 8 {
  47. angle = 270
  48. }
  49. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  50. flip = true
  51. }
  52. }
  53. if (angle+baseAngle)%180 != 0 {
  54. width, height = height, width
  55. }
  56. return width, height, angle, flip
  57. }
  58. func calcScale(width, height int, po *processingOptions, imgtype imageType) float64 {
  59. var shrink float64
  60. srcW, srcH := float64(width), float64(height)
  61. dstW, dstH := float64(po.Width), float64(po.Height)
  62. if po.Width == 0 {
  63. dstW = srcW
  64. }
  65. if po.Height == 0 {
  66. dstH = srcH
  67. }
  68. if dstW == srcW && dstH == srcH {
  69. shrink = 1
  70. } else {
  71. wshrink := srcW / dstW
  72. hshrink := srcH / dstH
  73. rt := po.ResizingType
  74. if rt == resizeAuto {
  75. srcD := width - height
  76. dstD := po.Width - po.Height
  77. if (srcD >= 0 && dstD >= 0) || (srcD < 0 && dstD < 0) {
  78. rt = resizeFill
  79. } else {
  80. rt = resizeFit
  81. }
  82. }
  83. switch {
  84. case po.Width == 0:
  85. shrink = hshrink
  86. case po.Height == 0:
  87. shrink = wshrink
  88. case rt == resizeFit:
  89. shrink = math.Max(wshrink, hshrink)
  90. default:
  91. shrink = math.Min(wshrink, hshrink)
  92. }
  93. }
  94. if !po.Enlarge && shrink < 1 && imgtype != imageTypeSVG {
  95. shrink = 1
  96. }
  97. shrink /= po.Dpr
  98. if shrink > srcW {
  99. shrink = srcW
  100. }
  101. if shrink > srcH {
  102. shrink = srcH
  103. }
  104. return 1.0 / shrink
  105. }
  106. func canScaleOnLoad(imgtype imageType, scale float64) bool {
  107. if imgtype == imageTypeSVG {
  108. return true
  109. }
  110. if conf.DisableShrinkOnLoad || scale >= 1 {
  111. return false
  112. }
  113. return imgtype == imageTypeJPEG || imgtype == imageTypeWEBP
  114. }
  115. func canFitToBytes(imgtype imageType) bool {
  116. switch imgtype {
  117. case imageTypeJPEG, imageTypeWEBP, imageTypeAVIF, imageTypeTIFF:
  118. return true
  119. default:
  120. return false
  121. }
  122. }
  123. func calcJpegShink(scale float64, imgtype imageType) int {
  124. shrink := int(1.0 / scale)
  125. switch {
  126. case shrink >= 8:
  127. return 8
  128. case shrink >= 4:
  129. return 4
  130. case shrink >= 2:
  131. return 2
  132. }
  133. return 1
  134. }
  135. func calcCropSize(orig int, crop float64) int {
  136. switch {
  137. case crop == 0.0:
  138. return 0
  139. case crop >= 1.0:
  140. return int(crop)
  141. default:
  142. return maxInt(1, scaleInt(orig, crop))
  143. }
  144. }
  145. func calcPosition(width, height, innerWidth, innerHeight int, gravity *gravityOptions, allowOverflow bool) (left, top int) {
  146. if gravity.Type == gravityFocusPoint {
  147. pointX := scaleInt(width, gravity.X)
  148. pointY := scaleInt(height, gravity.Y)
  149. left = pointX - innerWidth/2
  150. top = pointY - innerHeight/2
  151. } else {
  152. offX, offY := int(gravity.X), int(gravity.Y)
  153. left = (width-innerWidth+1)/2 + offX
  154. top = (height-innerHeight+1)/2 + offY
  155. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  156. top = 0 + offY
  157. }
  158. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  159. left = width - innerWidth - offX
  160. }
  161. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  162. top = height - innerHeight - offY
  163. }
  164. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  165. left = 0 + offX
  166. }
  167. }
  168. var minX, maxX, minY, maxY int
  169. if allowOverflow {
  170. minX, maxX = -innerWidth+1, width-1
  171. minY, maxY = -innerHeight+1, height-1
  172. } else {
  173. minX, maxX = 0, width-innerWidth
  174. minY, maxY = 0, height-innerHeight
  175. }
  176. left = maxInt(minX, minInt(left, maxX))
  177. top = maxInt(minY, minInt(top, maxY))
  178. return
  179. }
  180. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  181. if cropWidth == 0 && cropHeight == 0 {
  182. return nil
  183. }
  184. imgWidth, imgHeight := img.Width(), img.Height()
  185. cropWidth = minNonZeroInt(cropWidth, imgWidth)
  186. cropHeight = minNonZeroInt(cropHeight, imgHeight)
  187. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  188. return nil
  189. }
  190. if gravity.Type == gravitySmart {
  191. if err := img.CopyMemory(); err != nil {
  192. return err
  193. }
  194. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  195. return err
  196. }
  197. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  198. // so we have to copy memory after it
  199. return img.CopyMemory()
  200. }
  201. left, top := calcPosition(imgWidth, imgHeight, cropWidth, cropHeight, gravity, false)
  202. return img.Crop(left, top, cropWidth, cropHeight)
  203. }
  204. func prepareWatermark(wm *vipsImage, wmData *imageData, opts *watermarkOptions, imgWidth, imgHeight int) error {
  205. if err := wm.Load(wmData.Data, wmData.Type, 1, 1.0, 1); err != nil {
  206. return err
  207. }
  208. po := newProcessingOptions()
  209. po.ResizingType = resizeFit
  210. po.Dpr = 1
  211. po.Enlarge = true
  212. po.Format = wmData.Type
  213. if opts.Scale > 0 {
  214. po.Width = maxInt(scaleInt(imgWidth, opts.Scale), 1)
  215. po.Height = maxInt(scaleInt(imgHeight, opts.Scale), 1)
  216. }
  217. if err := transformImage(context.Background(), wm, wmData.Data, po, wmData.Type); err != nil {
  218. return err
  219. }
  220. if err := wm.EnsureAlpha(); err != nil {
  221. return nil
  222. }
  223. if opts.Replicate {
  224. return wm.Replicate(imgWidth, imgHeight)
  225. }
  226. left, top := calcPosition(imgWidth, imgHeight, wm.Width(), wm.Height(), &opts.Gravity, true)
  227. return wm.Embed(imgWidth, imgHeight, left, top, rgbColor{0, 0, 0}, true)
  228. }
  229. func applyWatermark(img *vipsImage, wmData *imageData, opts *watermarkOptions, framesCount int) error {
  230. if err := img.RgbColourspace(); err != nil {
  231. return err
  232. }
  233. if err := img.CopyMemory(); err != nil {
  234. return err
  235. }
  236. wm := new(vipsImage)
  237. defer wm.Clear()
  238. width := img.Width()
  239. height := img.Height()
  240. if err := prepareWatermark(wm, wmData, opts, width, height/framesCount); err != nil {
  241. return err
  242. }
  243. if framesCount > 1 {
  244. if err := wm.Replicate(width, height); err != nil {
  245. return err
  246. }
  247. }
  248. opacity := opts.Opacity * conf.WatermarkOpacity
  249. return img.ApplyWatermark(wm, opacity)
  250. }
  251. func copyMemoryAndCheckTimeout(ctx context.Context, img *vipsImage) error {
  252. err := img.CopyMemory()
  253. checkTimeout(ctx)
  254. return err
  255. }
  256. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  257. var (
  258. err error
  259. trimmed bool
  260. )
  261. if po.Trim.Enabled {
  262. if err = img.Trim(po.Trim.Threshold, po.Trim.Smart, po.Trim.Color, po.Trim.EqualHor, po.Trim.EqualVer); err != nil {
  263. return err
  264. }
  265. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  266. return err
  267. }
  268. trimmed = true
  269. }
  270. srcWidth, srcHeight, angle, flip := extractMeta(img, po.Rotate, po.AutoRotate)
  271. cropWidth := calcCropSize(srcWidth, po.Crop.Width)
  272. cropHeight := calcCropSize(srcHeight, po.Crop.Height)
  273. cropGravity := po.Crop.Gravity
  274. if cropGravity.Type == gravityUnknown {
  275. cropGravity = po.Gravity
  276. }
  277. widthToScale := minNonZeroInt(cropWidth, srcWidth)
  278. heightToScale := minNonZeroInt(cropHeight, srcHeight)
  279. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  280. if cropWidth > 0 {
  281. cropWidth = maxInt(1, scaleInt(cropWidth, scale))
  282. }
  283. if cropHeight > 0 {
  284. cropHeight = maxInt(1, scaleInt(cropHeight, scale))
  285. }
  286. if cropGravity.Type != gravityFocusPoint {
  287. cropGravity.X *= scale
  288. cropGravity.Y *= scale
  289. }
  290. if !trimmed && scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  291. jpegShrink := calcJpegShink(scale, imgtype)
  292. if imgtype != imageTypeJPEG || jpegShrink != 1 {
  293. // Do some scale-on-load
  294. if err = img.Load(data, imgtype, jpegShrink, scale, 1); err != nil {
  295. return err
  296. }
  297. }
  298. // Update scale after scale-on-load
  299. newWidth, newHeight, _, _ := extractMeta(img, po.Rotate, po.AutoRotate)
  300. if srcWidth > srcHeight {
  301. scale = float64(srcWidth) * scale / float64(newWidth)
  302. } else {
  303. scale = float64(srcHeight) * scale / float64(newHeight)
  304. }
  305. if srcWidth == scaleInt(srcWidth, scale) && srcHeight == scaleInt(srcHeight, scale) {
  306. scale = 1.0
  307. }
  308. }
  309. if err = img.Rad2Float(); err != nil {
  310. return err
  311. }
  312. iccImported := false
  313. convertToLinear := conf.UseLinearColorspace && scale != 1
  314. if convertToLinear || !img.IsSRGB() {
  315. if err = img.ImportColourProfile(); err != nil {
  316. return err
  317. }
  318. iccImported = true
  319. }
  320. if convertToLinear {
  321. if err = img.LinearColourspace(); err != nil {
  322. return err
  323. }
  324. } else {
  325. if err = img.RgbColourspace(); err != nil {
  326. return err
  327. }
  328. }
  329. hasAlpha := img.HasAlpha()
  330. if scale != 1 {
  331. if err = img.Resize(scale, hasAlpha); err != nil {
  332. return err
  333. }
  334. }
  335. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  336. return err
  337. }
  338. if err = img.Rotate(angle); err != nil {
  339. return err
  340. }
  341. if flip {
  342. if err = img.Flip(); err != nil {
  343. return err
  344. }
  345. }
  346. if err = img.Rotate(po.Rotate); err != nil {
  347. return err
  348. }
  349. dprWidth := scaleInt(po.Width, po.Dpr)
  350. dprHeight := scaleInt(po.Height, po.Dpr)
  351. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  352. return err
  353. }
  354. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  355. return err
  356. }
  357. if po.Format == imageTypeWEBP {
  358. webpLimitShrink := float64(maxInt(img.Width(), img.Height())) / webpMaxDimension
  359. if webpLimitShrink > 1.0 {
  360. if err = img.Resize(1.0/webpLimitShrink, hasAlpha); err != nil {
  361. return err
  362. }
  363. logWarning("WebP dimension size is limited to %d. The image is rescaled to %dx%d", int(webpMaxDimension), img.Width(), img.Height())
  364. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  365. return err
  366. }
  367. }
  368. }
  369. keepProfile := !po.StripColorProfile && po.Format.SupportsColourProfile()
  370. if iccImported {
  371. if keepProfile {
  372. // We imported ICC profile and want to keep it,
  373. // so we need to export it
  374. if err = img.ExportColourProfile(); err != nil {
  375. return err
  376. }
  377. } else {
  378. // We imported ICC profile but don't want to keep it,
  379. // so we need to export image to sRGB for maximum compatibility
  380. if err = img.ExportColourProfileToSRGB(); err != nil {
  381. return err
  382. }
  383. }
  384. } else if !keepProfile {
  385. // We don't import ICC profile and don't want to keep it,
  386. // so we need to transform it to sRGB for maximum compatibility
  387. if err = img.TransformColourProfile(); err != nil {
  388. return err
  389. }
  390. }
  391. if err = img.RgbColourspace(); err != nil {
  392. return err
  393. }
  394. if !keepProfile {
  395. if err = img.RemoveColourProfile(); err != nil {
  396. return err
  397. }
  398. }
  399. transparentBg := po.Format.SupportsAlpha() && !po.Flatten
  400. if hasAlpha && !transparentBg {
  401. if err = img.Flatten(po.Background); err != nil {
  402. return err
  403. }
  404. }
  405. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  406. return err
  407. }
  408. if po.Blur > 0 {
  409. if err = img.Blur(po.Blur); err != nil {
  410. return err
  411. }
  412. }
  413. if po.Sharpen > 0 {
  414. if err = img.Sharpen(po.Sharpen); err != nil {
  415. return err
  416. }
  417. }
  418. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  419. return err
  420. }
  421. if po.Extend.Enabled && (dprWidth > img.Width() || dprHeight > img.Height()) {
  422. offX, offY := calcPosition(dprWidth, dprHeight, img.Width(), img.Height(), &po.Extend.Gravity, false)
  423. if err = img.Embed(dprWidth, dprHeight, offX, offY, po.Background, transparentBg); err != nil {
  424. return err
  425. }
  426. }
  427. if po.Padding.Enabled {
  428. paddingTop := scaleInt(po.Padding.Top, po.Dpr)
  429. paddingRight := scaleInt(po.Padding.Right, po.Dpr)
  430. paddingBottom := scaleInt(po.Padding.Bottom, po.Dpr)
  431. paddingLeft := scaleInt(po.Padding.Left, po.Dpr)
  432. if err = img.Embed(
  433. img.Width()+paddingLeft+paddingRight,
  434. img.Height()+paddingTop+paddingBottom,
  435. paddingLeft,
  436. paddingTop,
  437. po.Background,
  438. transparentBg,
  439. ); err != nil {
  440. return err
  441. }
  442. }
  443. if po.Watermark.Enabled && watermark != nil {
  444. if err = applyWatermark(img, watermark, &po.Watermark, 1); err != nil {
  445. return err
  446. }
  447. }
  448. if err = img.RgbColourspace(); err != nil {
  449. return err
  450. }
  451. if err := img.CastUchar(); err != nil {
  452. return err
  453. }
  454. if po.StripMetadata {
  455. if err := img.Strip(); err != nil {
  456. return err
  457. }
  458. }
  459. return copyMemoryAndCheckTimeout(ctx, img)
  460. }
  461. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  462. if po.Trim.Enabled {
  463. logWarning("Trim is not supported for animated images")
  464. po.Trim.Enabled = false
  465. }
  466. imgWidth := img.Width()
  467. frameHeight, err := img.GetInt("page-height")
  468. if err != nil {
  469. return err
  470. }
  471. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  472. // Double check dimensions because animated image has many frames
  473. if err = checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  474. return err
  475. }
  476. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  477. if nPages, _ := img.GetIntDefault("n-pages", 0); nPages > framesCount {
  478. // Load only the needed frames
  479. if err = img.Load(data, imgtype, 1, 1.0, framesCount); err != nil {
  480. return err
  481. }
  482. }
  483. delay, err := img.GetIntSliceDefault("delay", nil)
  484. if err != nil {
  485. return err
  486. }
  487. loop, err := img.GetIntDefault("loop", 0)
  488. if err != nil {
  489. return err
  490. }
  491. // Legacy fields
  492. // TODO: remove this in major update
  493. gifLoop, err := img.GetIntDefault("gif-loop", -1)
  494. if err != nil {
  495. return err
  496. }
  497. gifDelay, err := img.GetIntDefault("gif-delay", -1)
  498. if err != nil {
  499. return err
  500. }
  501. watermarkEnabled := po.Watermark.Enabled
  502. po.Watermark.Enabled = false
  503. defer func() { po.Watermark.Enabled = watermarkEnabled }()
  504. frames := make([]*vipsImage, framesCount)
  505. defer func() {
  506. for _, frame := range frames {
  507. if frame != nil {
  508. frame.Clear()
  509. }
  510. }
  511. }()
  512. for i := 0; i < framesCount; i++ {
  513. frame := new(vipsImage)
  514. if err = img.Extract(frame, 0, i*frameHeight, imgWidth, frameHeight); err != nil {
  515. return err
  516. }
  517. frames[i] = frame
  518. if err = transformImage(ctx, frame, nil, po, imgtype); err != nil {
  519. return err
  520. }
  521. if err = copyMemoryAndCheckTimeout(ctx, frame); err != nil {
  522. return err
  523. }
  524. }
  525. if err = img.Arrayjoin(frames); err != nil {
  526. return err
  527. }
  528. if watermarkEnabled && watermark != nil {
  529. if err = applyWatermark(img, watermark, &po.Watermark, framesCount); err != nil {
  530. return err
  531. }
  532. }
  533. if err = img.CastUchar(); err != nil {
  534. return err
  535. }
  536. if err = copyMemoryAndCheckTimeout(ctx, img); err != nil {
  537. return err
  538. }
  539. if len(delay) == 0 {
  540. delay = make([]int, framesCount)
  541. for i := range delay {
  542. delay[i] = 40
  543. }
  544. } else if len(delay) > framesCount {
  545. delay = delay[:framesCount]
  546. }
  547. img.SetInt("page-height", frames[0].Height())
  548. img.SetIntSlice("delay", delay)
  549. img.SetInt("loop", loop)
  550. img.SetInt("n-pages", framesCount)
  551. // Legacy fields
  552. // TODO: remove this in major update
  553. if gifLoop >= 0 {
  554. img.SetInt("gif-loop", gifLoop)
  555. }
  556. if gifDelay >= 0 {
  557. img.SetInt("gif-delay", gifDelay)
  558. }
  559. return nil
  560. }
  561. func getIcoData(imgdata *imageData) (*imageData, error) {
  562. icoMeta, err := imagemeta.DecodeIcoMeta(bytes.NewReader(imgdata.Data))
  563. if err != nil {
  564. return nil, err
  565. }
  566. offset := icoMeta.BestImageOffset()
  567. size := icoMeta.BestImageSize()
  568. data := imgdata.Data[offset : offset+size]
  569. var format string
  570. meta, err := imagemeta.DecodeMeta(bytes.NewReader(data))
  571. if err != nil {
  572. // Looks like it's BMP with an incomplete header
  573. if d, err := imagemeta.FixBmpHeader(data); err == nil {
  574. format = "bmp"
  575. data = d
  576. } else {
  577. return nil, err
  578. }
  579. } else {
  580. format = meta.Format()
  581. }
  582. if imgtype, ok := imageTypes[format]; ok && vipsTypeSupportLoad[imgtype] {
  583. return &imageData{
  584. Data: data,
  585. Type: imgtype,
  586. }, nil
  587. }
  588. return nil, fmt.Errorf("Can't load %s from ICO", meta.Format())
  589. }
  590. func saveImageToFitBytes(ctx context.Context, po *processingOptions, img *vipsImage) ([]byte, context.CancelFunc, error) {
  591. var diff float64
  592. quality := po.getQuality()
  593. for {
  594. result, cancel, err := img.Save(po.Format, quality)
  595. if len(result) <= po.MaxBytes || quality <= 10 || err != nil {
  596. return result, cancel, err
  597. }
  598. cancel()
  599. checkTimeout(ctx)
  600. delta := float64(len(result)) / float64(po.MaxBytes)
  601. switch {
  602. case delta > 3:
  603. diff = 0.25
  604. case delta > 1.5:
  605. diff = 0.5
  606. default:
  607. diff = 0.75
  608. }
  609. quality = int(float64(quality) * diff)
  610. }
  611. }
  612. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  613. runtime.LockOSThread()
  614. defer runtime.UnlockOSThread()
  615. defer startDataDogSpan(ctx, "processing_image")()
  616. defer startNewRelicSegment(ctx, "Processing image")()
  617. defer startPrometheusDuration(prometheusProcessingDuration)()
  618. defer vipsCleanup()
  619. po := getProcessingOptions(ctx)
  620. imgdata := getImageData(ctx)
  621. switch {
  622. case po.Format == imageTypeUnknown:
  623. switch {
  624. case po.PreferAvif && canSwitchFormat(imgdata.Type, imageTypeUnknown, imageTypeAVIF):
  625. po.Format = imageTypeAVIF
  626. case po.PreferWebP && canSwitchFormat(imgdata.Type, imageTypeUnknown, imageTypeWEBP):
  627. po.Format = imageTypeWEBP
  628. case imageTypeSaveSupport(imgdata.Type) && imageTypeGoodForWeb(imgdata.Type):
  629. po.Format = imgdata.Type
  630. default:
  631. po.Format = imageTypeJPEG
  632. }
  633. case po.EnforceAvif && canSwitchFormat(imgdata.Type, po.Format, imageTypeAVIF):
  634. po.Format = imageTypeAVIF
  635. case po.EnforceWebP && canSwitchFormat(imgdata.Type, po.Format, imageTypeWEBP):
  636. po.Format = imageTypeWEBP
  637. }
  638. if po.Format == imageTypeSVG {
  639. if imgdata.Type != imageTypeSVG {
  640. return []byte{}, func() {}, errConvertingNonSvgToSvg
  641. }
  642. return imgdata.Data, func() {}, nil
  643. }
  644. if imgdata.Type == imageTypeSVG && !vipsTypeSupportLoad[imageTypeSVG] {
  645. return []byte{}, func() {}, errSourceImageTypeNotSupported
  646. }
  647. if imgdata.Type == imageTypeICO {
  648. icodata, err := getIcoData(imgdata)
  649. if err != nil {
  650. return nil, func() {}, err
  651. }
  652. imgdata = icodata
  653. }
  654. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgdata.Type) && vipsSupportAnimation(po.Format)
  655. pages := 1
  656. if animationSupport {
  657. pages = -1
  658. }
  659. img := new(vipsImage)
  660. defer img.Clear()
  661. if err := img.Load(imgdata.Data, imgdata.Type, 1, 1.0, pages); err != nil {
  662. return nil, func() {}, err
  663. }
  664. if animationSupport && img.IsAnimated() {
  665. if err := transformAnimated(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  666. return nil, func() {}, err
  667. }
  668. } else {
  669. if err := transformImage(ctx, img, imgdata.Data, po, imgdata.Type); err != nil {
  670. return nil, func() {}, err
  671. }
  672. }
  673. if err := copyMemoryAndCheckTimeout(ctx, img); err != nil {
  674. return nil, func() {}, err
  675. }
  676. if po.MaxBytes > 0 && canFitToBytes(po.Format) {
  677. return saveImageToFitBytes(ctx, po, img)
  678. }
  679. return img.Save(po.Format, po.getQuality())
  680. }