image-utils.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import { copy, remove } from 'fs-extra/esm'
  2. import { readFile, rename } from 'fs/promises'
  3. import { ColorActionName } from '@jimp/plugin-color'
  4. import { buildUUID, getLowercaseExtension } from '@peertube/peertube-node-utils'
  5. import { convertWebPToJPG, processGIF } from './ffmpeg/index.js'
  6. import { logger } from './logger.js'
  7. import type Jimp from 'jimp'
  8. export function generateImageFilename (extension = '.jpg') {
  9. return buildUUID() + extension
  10. }
  11. export async function processImage (options: {
  12. path: string
  13. destination: string
  14. newSize: { width: number, height: number }
  15. keepOriginal?: boolean // default false
  16. }) {
  17. const { path, destination, newSize, keepOriginal = false } = options
  18. const extension = getLowercaseExtension(path)
  19. if (path === destination) {
  20. throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
  21. }
  22. logger.debug('Processing image %s to %s.', path, destination)
  23. // Use FFmpeg to process GIF
  24. if (extension === '.gif') {
  25. await processGIF({ path, destination, newSize })
  26. } else {
  27. await jimpProcessor(path, destination, newSize, extension)
  28. }
  29. if (keepOriginal !== true) await remove(path)
  30. logger.debug('Finished processing image %s to %s.', path, destination)
  31. }
  32. export async function getImageSize (path: string) {
  33. const inputBuffer = await readFile(path)
  34. const Jimp = await import('jimp')
  35. const image = await Jimp.default.read(inputBuffer)
  36. return {
  37. width: image.getWidth(),
  38. height: image.getHeight()
  39. }
  40. }
  41. // ---------------------------------------------------------------------------
  42. // Private
  43. // ---------------------------------------------------------------------------
  44. async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
  45. let sourceImage: Jimp
  46. const inputBuffer = await readFile(path)
  47. const Jimp = await import('jimp')
  48. try {
  49. sourceImage = await Jimp.default.read(inputBuffer)
  50. } catch (err) {
  51. logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
  52. const newName = path + '.jpg'
  53. await convertWebPToJPG({ path, destination: newName })
  54. await rename(newName, path)
  55. sourceImage = await Jimp.default.read(path)
  56. }
  57. await remove(destination)
  58. // Optimization if the source file has the appropriate size
  59. const outputExt = getLowercaseExtension(destination)
  60. if (skipProcessing({ sourceImage, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
  61. return copy(path, destination)
  62. }
  63. await autoResize({ sourceImage, newSize, destination })
  64. }
  65. async function autoResize (options: {
  66. sourceImage: Jimp
  67. newSize: { width: number, height: number }
  68. destination: string
  69. }) {
  70. const { sourceImage, newSize, destination } = options
  71. // Portrait mode targeting a landscape, apply some effect on the image
  72. const sourceIsPortrait = sourceImage.getWidth() <= sourceImage.getHeight()
  73. const destIsPortraitOrSquare = newSize.width <= newSize.height
  74. removeExif(sourceImage)
  75. if (sourceIsPortrait && !destIsPortraitOrSquare) {
  76. const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
  77. .color([ { apply: ColorActionName.SHADE, params: [ 50 ] } ])
  78. const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
  79. return write(baseImage.blit(topImage, 0, 0), destination)
  80. }
  81. return write(sourceImage.cover(newSize.width, newSize.height), destination)
  82. }
  83. function write (image: Jimp, destination: string) {
  84. return image.quality(80).writeAsync(destination)
  85. }
  86. function skipProcessing (options: {
  87. sourceImage: Jimp
  88. newSize: { width: number, height: number }
  89. imageBytes: number
  90. inputExt: string
  91. outputExt: string
  92. }) {
  93. const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
  94. const { width, height } = newSize
  95. if (hasExif(sourceImage)) return false
  96. if (sourceImage.getWidth() > width || sourceImage.getHeight() > height) return false
  97. if (inputExt !== outputExt) return false
  98. const kB = 1000
  99. if (height >= 1000) return imageBytes <= 200 * kB
  100. if (height >= 500) return imageBytes <= 100 * kB
  101. return imageBytes <= 15 * kB
  102. }
  103. function hasExif (image: Jimp) {
  104. return !!(image.bitmap as any).exifBuffer
  105. }
  106. function removeExif (image: Jimp) {
  107. (image.bitmap as any).exifBuffer = null
  108. }