image-utils.ts 5.1 KB

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