process.go 20 KB

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