process.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package main
  2. import (
  3. "context"
  4. "math"
  5. "runtime"
  6. "golang.org/x/sync/errgroup"
  7. )
  8. const msgSmartCropNotSupported = "Smart crop is not supported by used version of libvips"
  9. func extractMeta(img *vipsImage) (int, int, int, bool) {
  10. width := img.Width()
  11. height := img.Height()
  12. angle := vipsAngleD0
  13. flip := false
  14. orientation := img.Orientation()
  15. if orientation >= 5 && orientation <= 8 {
  16. width, height = height, width
  17. }
  18. if orientation == 3 || orientation == 4 {
  19. angle = vipsAngleD180
  20. }
  21. if orientation == 5 || orientation == 6 {
  22. angle = vipsAngleD90
  23. }
  24. if orientation == 7 || orientation == 8 {
  25. angle = vipsAngleD270
  26. }
  27. if orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7 {
  28. flip = true
  29. }
  30. return width, height, angle, flip
  31. }
  32. func calcScale(width, height int, po *processingOptions, imgtype imageType) float64 {
  33. var scale float64
  34. srcW, srcH := float64(width), float64(height)
  35. if (po.Width == 0 || po.Width == width) && (po.Height == 0 || po.Height == height) {
  36. scale = 1
  37. } else {
  38. wr := float64(po.Width) / srcW
  39. hr := float64(po.Height) / srcH
  40. rt := po.Resize
  41. if rt == resizeAuto {
  42. srcD := width - height
  43. dstD := po.Width - po.Height
  44. if (srcD >= 0 && dstD >= 0) || (srcD < 0 && dstD < 0) {
  45. rt = resizeFill
  46. } else {
  47. rt = resizeFit
  48. }
  49. }
  50. if po.Width == 0 {
  51. scale = hr
  52. } else if po.Height == 0 {
  53. scale = wr
  54. } else if rt == resizeFit {
  55. scale = math.Min(wr, hr)
  56. } else {
  57. scale = math.Max(wr, hr)
  58. }
  59. }
  60. scale = scale * po.Dpr
  61. if !po.Enlarge && scale > 1 && imgtype != imageTypeSVG {
  62. return 1
  63. }
  64. if srcW*scale < 1 {
  65. scale = 1 / srcW
  66. }
  67. if srcH*scale < 1 {
  68. scale = 1 / srcH
  69. }
  70. return scale
  71. }
  72. func canScaleOnLoad(imgtype imageType, scale float64) bool {
  73. if imgtype == imageTypeSVG {
  74. return true
  75. }
  76. if conf.DisableShrinkOnLoad || scale >= 1 {
  77. return false
  78. }
  79. return imgtype == imageTypeJPEG || imgtype == imageTypeWEBP
  80. }
  81. func calcJpegShink(scale float64, imgtype imageType) int {
  82. shrink := int(1.0 / scale)
  83. switch {
  84. case shrink >= 8:
  85. return 8
  86. case shrink >= 4:
  87. return 4
  88. case shrink >= 2:
  89. return 2
  90. }
  91. return 1
  92. }
  93. func calcCrop(width, height, cropWidth, cropHeight int, gravity *gravityOptions) (left, top int) {
  94. if gravity.Type == gravityFocusPoint {
  95. pointX := int(float64(width) * gravity.X)
  96. pointY := int(float64(height) * gravity.Y)
  97. left = maxInt(0, minInt(pointX-cropWidth/2, width-cropWidth))
  98. top = maxInt(0, minInt(pointY-cropHeight/2, height-cropHeight))
  99. return
  100. }
  101. offX, offY := int(gravity.X), int(gravity.Y)
  102. left = (width-cropWidth+1)/2 + offX
  103. top = (height-cropHeight+1)/2 + offY
  104. if gravity.Type == gravityNorth || gravity.Type == gravityNorthEast || gravity.Type == gravityNorthWest {
  105. top = 0 + offY
  106. }
  107. if gravity.Type == gravityEast || gravity.Type == gravityNorthEast || gravity.Type == gravitySouthEast {
  108. left = width - cropWidth - offX
  109. }
  110. if gravity.Type == gravitySouth || gravity.Type == gravitySouthEast || gravity.Type == gravitySouthWest {
  111. top = height - cropHeight - offY
  112. }
  113. if gravity.Type == gravityWest || gravity.Type == gravityNorthWest || gravity.Type == gravitySouthWest {
  114. left = 0 + offX
  115. }
  116. left = maxInt(0, minInt(left, width-cropWidth))
  117. top = maxInt(0, minInt(top, height-cropHeight))
  118. return
  119. }
  120. func cropImage(img *vipsImage, cropWidth, cropHeight int, gravity *gravityOptions) error {
  121. if cropWidth == 0 && cropHeight == 0 {
  122. return nil
  123. }
  124. imgWidth, imgHeight := img.Width(), img.Height()
  125. if cropWidth == 0 {
  126. cropWidth = imgWidth
  127. } else {
  128. cropWidth = minInt(cropWidth, imgWidth)
  129. }
  130. if cropHeight == 0 {
  131. cropHeight = imgHeight
  132. } else {
  133. cropHeight = minInt(cropHeight, imgHeight)
  134. }
  135. if cropWidth >= imgWidth && cropHeight >= imgHeight {
  136. return nil
  137. }
  138. if gravity.Type == gravitySmart {
  139. if err := img.CopyMemory(); err != nil {
  140. return err
  141. }
  142. if err := img.SmartCrop(cropWidth, cropHeight); err != nil {
  143. return err
  144. }
  145. // Applying additional modifications after smart crop causes SIGSEGV on Alpine
  146. // so we have to copy memory after it
  147. return img.CopyMemory()
  148. }
  149. left, top := calcCrop(imgWidth, imgHeight, cropWidth, cropHeight, gravity)
  150. return img.Crop(left, top, cropWidth, cropHeight)
  151. }
  152. func scaleSize(size int, scale float64) int {
  153. if size == 0 {
  154. return 0
  155. }
  156. return roundToInt(float64(size) * scale)
  157. }
  158. func transformImage(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  159. var err error
  160. srcWidth, srcHeight, angle, flip := extractMeta(img)
  161. cropWidth, cropHeight := po.Crop.Width, po.Crop.Height
  162. cropGravity := po.Crop.Gravity
  163. if cropGravity.Type == gravityUnknown {
  164. cropGravity = po.Gravity
  165. }
  166. widthToScale, heightToScale := srcWidth, srcHeight
  167. if cropWidth > 0 {
  168. widthToScale = minInt(cropWidth, srcWidth)
  169. }
  170. if cropHeight > 0 {
  171. heightToScale = minInt(cropHeight, srcHeight)
  172. }
  173. scale := calcScale(widthToScale, heightToScale, po, imgtype)
  174. cropWidth = scaleSize(cropWidth, scale)
  175. cropHeight = scaleSize(cropHeight, scale)
  176. cropGravity.X = cropGravity.X * scale
  177. cropGravity.Y = cropGravity.Y * scale
  178. if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
  179. if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
  180. // Do some scale-on-load
  181. if err := img.Load(data, imgtype, 1, scale, 1); err != nil {
  182. return err
  183. }
  184. } else if imgtype == imageTypeJPEG {
  185. // Do some shrink-on-load
  186. if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
  187. if err := img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
  188. return err
  189. }
  190. }
  191. }
  192. // Update scale after scale-on-load
  193. newWidth, newHeight, _, _ := extractMeta(img)
  194. widthToScale = scaleSize(widthToScale, float64(newWidth)/float64(srcWidth))
  195. heightToScale = scaleSize(heightToScale, float64(newHeight)/float64(srcHeight))
  196. scale = calcScale(widthToScale, heightToScale, po, imgtype)
  197. }
  198. if err = img.Rad2Float(); err != nil {
  199. return err
  200. }
  201. iccImported := false
  202. convertToLinear := conf.UseLinearColorspace && (scale != 1 || po.Dpr != 1)
  203. if convertToLinear || !img.IsSRGB() {
  204. if err = img.ImportColourProfile(true); err != nil {
  205. return err
  206. }
  207. iccImported = true
  208. }
  209. if convertToLinear {
  210. if err = img.LinearColourspace(); err != nil {
  211. return err
  212. }
  213. } else {
  214. if err = img.RgbColourspace(); err != nil {
  215. return err
  216. }
  217. }
  218. hasAlpha := img.HasAlpha()
  219. if scale != 1 {
  220. if err = img.Resize(scale, hasAlpha); err != nil {
  221. return err
  222. }
  223. }
  224. checkTimeout(ctx)
  225. if angle != vipsAngleD0 || flip {
  226. if err = img.CopyMemory(); err != nil {
  227. return err
  228. }
  229. if angle != vipsAngleD0 {
  230. if err = img.Rotate(angle); err != nil {
  231. return err
  232. }
  233. }
  234. if flip {
  235. if err = img.Flip(); err != nil {
  236. return err
  237. }
  238. }
  239. }
  240. checkTimeout(ctx)
  241. dprWidth := roundToInt(float64(po.Width) * po.Dpr)
  242. dprHeight := roundToInt(float64(po.Height) * po.Dpr)
  243. if cropGravity.Type == po.Gravity.Type && cropGravity.Type != gravityFocusPoint {
  244. if cropWidth == 0 {
  245. cropWidth = dprWidth
  246. } else if dprWidth > 0 {
  247. cropWidth = minInt(cropWidth, dprWidth)
  248. }
  249. if cropHeight == 0 {
  250. cropHeight = dprHeight
  251. } else if dprHeight > 0 {
  252. cropHeight = minInt(cropHeight, dprHeight)
  253. }
  254. sumGravity := gravityOptions{
  255. Type: cropGravity.Type,
  256. X: cropGravity.X + po.Gravity.X,
  257. Y: cropGravity.Y + po.Gravity.Y,
  258. }
  259. if err = cropImage(img, cropWidth, cropHeight, &sumGravity); err != nil {
  260. return err
  261. }
  262. } else {
  263. if err = cropImage(img, cropWidth, cropHeight, &cropGravity); err != nil {
  264. return err
  265. }
  266. if err = cropImage(img, dprWidth, dprHeight, &po.Gravity); err != nil {
  267. return err
  268. }
  269. }
  270. checkTimeout(ctx)
  271. if !iccImported {
  272. if err = img.ImportColourProfile(false); err != nil {
  273. return err
  274. }
  275. }
  276. if err = img.RgbColourspace(); err != nil {
  277. return err
  278. }
  279. if hasAlpha && (po.Flatten || po.Format == imageTypeJPEG) {
  280. if err = img.Flatten(po.Background); err != nil {
  281. return err
  282. }
  283. }
  284. if po.Blur > 0 {
  285. if err = img.Blur(po.Blur); err != nil {
  286. return err
  287. }
  288. }
  289. if po.Sharpen > 0 {
  290. if err = img.Sharpen(po.Sharpen); err != nil {
  291. return err
  292. }
  293. }
  294. if po.Extend && (po.Width > img.Width() || po.Height > img.Height()) {
  295. if err = img.Embed(gravityCenter, po.Width, po.Height, 0, 0, po.Background); err != nil {
  296. return err
  297. }
  298. }
  299. checkTimeout(ctx)
  300. if po.Watermark.Enabled {
  301. if err = img.ApplyWatermark(&po.Watermark); err != nil {
  302. return err
  303. }
  304. }
  305. return img.RgbColourspace()
  306. }
  307. func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *processingOptions, imgtype imageType) error {
  308. imgWidth := img.Width()
  309. frameHeight, err := img.GetInt("page-height")
  310. if err != nil {
  311. return err
  312. }
  313. framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
  314. // Double check dimensions because animated image has many frames
  315. if err := checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
  316. return err
  317. }
  318. // Vips 8.8+ supports n-pages and doesn't load the whole animated image on header access
  319. if nPages, _ := img.GetInt("n-pages"); nPages > 0 {
  320. scale := 1.0
  321. // Don't do scale on load if we need to crop
  322. if po.Crop.Width == 0 && po.Crop.Height == 0 {
  323. scale = calcScale(imgWidth, frameHeight, po, imgtype)
  324. }
  325. if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
  326. logNotice("Animated scale on load")
  327. // Do some scale-on-load and load only the needed frames
  328. if err := img.Load(data, imgtype, 1, scale, framesCount); err != nil {
  329. return err
  330. }
  331. }
  332. imgWidth = img.Width()
  333. frameHeight, err = img.GetInt("page-height")
  334. if err != nil {
  335. return err
  336. }
  337. }
  338. delay, err := img.GetInt("gif-delay")
  339. if err != nil {
  340. return err
  341. }
  342. loop, err := img.GetInt("gif-loop")
  343. if err != nil {
  344. return err
  345. }
  346. frames := make([]*vipsImage, framesCount)
  347. defer func() {
  348. for _, frame := range frames {
  349. frame.Clear()
  350. }
  351. }()
  352. var errg errgroup.Group
  353. for i := 0; i < framesCount; i++ {
  354. ind := i
  355. errg.Go(func() error {
  356. frame := new(vipsImage)
  357. if err := img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
  358. return err
  359. }
  360. if err := transformImage(ctx, frame, nil, po, imgtype); err != nil {
  361. return err
  362. }
  363. frames[ind] = frame
  364. return nil
  365. })
  366. }
  367. if err := errg.Wait(); err != nil {
  368. return err
  369. }
  370. checkTimeout(ctx)
  371. if err := img.Arrayjoin(frames); err != nil {
  372. return err
  373. }
  374. img.SetInt("page-height", frames[0].Height())
  375. img.SetInt("gif-delay", delay)
  376. img.SetInt("gif-loop", loop)
  377. img.SetInt("n-pages", framesCount)
  378. return nil
  379. }
  380. func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
  381. runtime.LockOSThread()
  382. defer runtime.UnlockOSThread()
  383. if newRelicEnabled {
  384. newRelicCancel := startNewRelicSegment(ctx, "Processing image")
  385. defer newRelicCancel()
  386. }
  387. if prometheusEnabled {
  388. defer startPrometheusDuration(prometheusProcessingDuration)()
  389. }
  390. defer vipsCleanup()
  391. po := getProcessingOptions(ctx)
  392. data := getImageData(ctx).Bytes()
  393. imgtype := getImageType(ctx)
  394. if po.Format == imageTypeUnknown {
  395. if po.PreferWebP && vipsTypeSupportSave[imageTypeWEBP] {
  396. po.Format = imageTypeWEBP
  397. } else if vipsTypeSupportSave[imgtype] && imgtype != imageTypeHEIC {
  398. po.Format = imgtype
  399. } else {
  400. po.Format = imageTypeJPEG
  401. }
  402. } else if po.EnforceWebP && vipsTypeSupportSave[imageTypeWEBP] {
  403. po.Format = imageTypeWEBP
  404. }
  405. if !vipsSupportSmartcrop {
  406. if po.Gravity.Type == gravitySmart {
  407. logWarning(msgSmartCropNotSupported)
  408. po.Gravity.Type = gravityCenter
  409. }
  410. if po.Crop.Gravity.Type == gravitySmart {
  411. logWarning(msgSmartCropNotSupported)
  412. po.Crop.Gravity.Type = gravityCenter
  413. }
  414. }
  415. if po.Resize == resizeCrop {
  416. logWarning("`crop` resizing type is deprecated and will be removed in future versions. Use `crop` processing option instead")
  417. po.Crop.Width, po.Crop.Height = po.Width, po.Height
  418. po.Resize = resizeFit
  419. po.Width, po.Height = 0, 0
  420. }
  421. animationSupport := conf.MaxAnimationFrames > 1 && vipsSupportAnimation(imgtype) && vipsSupportAnimation(po.Format)
  422. pages := 1
  423. if animationSupport {
  424. pages = -1
  425. }
  426. img := new(vipsImage)
  427. defer img.Clear()
  428. if err := img.Load(data, imgtype, 1, 1.0, pages); err != nil {
  429. return nil, func() {}, err
  430. }
  431. if animationSupport && img.IsAnimated() {
  432. if err := transformAnimated(ctx, img, data, po, imgtype); err != nil {
  433. return nil, func() {}, err
  434. }
  435. } else {
  436. if err := transformImage(ctx, img, data, po, imgtype); err != nil {
  437. return nil, func() {}, err
  438. }
  439. }
  440. checkTimeout(ctx)
  441. if po.Format == imageTypeGIF {
  442. if err := img.CastUchar(); err != nil {
  443. return nil, func() {}, err
  444. }
  445. checkTimeout(ctx)
  446. }
  447. return img.Save(po.Format, po.Quality)
  448. }