process.go 17 KB

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