process.go 20 KB

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