image-utils.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 (
  13. path: string,
  14. destination: string,
  15. newSize: { width: number, height: number },
  16. keepOriginal = false
  17. ) {
  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. }
  31. async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
  32. const pendingImageName = 'pending-' + imageName
  33. const pendingImagePath = join(folder, pendingImageName)
  34. try {
  35. await generateThumbnailFromVideo(fromPath, folder, imageName)
  36. const destination = join(folder, imageName)
  37. await processImage(pendingImagePath, destination, size)
  38. } catch (err) {
  39. logger.error('Cannot generate image from video %s.', fromPath, { err, ...lTags() })
  40. try {
  41. await remove(pendingImagePath)
  42. } catch (err) {
  43. logger.debug('Cannot remove pending image path after generation error.', { err, ...lTags() })
  44. }
  45. }
  46. }
  47. async function getImageSize (path: string) {
  48. const inputBuffer = await readFile(path)
  49. const image = await jimpRead(inputBuffer)
  50. return {
  51. width: image.getWidth(),
  52. height: image.getHeight()
  53. }
  54. }
  55. // ---------------------------------------------------------------------------
  56. export {
  57. generateImageFilename,
  58. generateImageFromVideoFile,
  59. processImage,
  60. getImageSize
  61. }
  62. // ---------------------------------------------------------------------------
  63. async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
  64. let sourceImage: Jimp
  65. const inputBuffer = await readFile(path)
  66. try {
  67. sourceImage = await jimpRead(inputBuffer)
  68. } catch (err) {
  69. logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
  70. const newName = path + '.jpg'
  71. await convertWebPToJPG(path, newName)
  72. await rename(newName, path)
  73. sourceImage = await jimpRead(path)
  74. }
  75. await remove(destination)
  76. // Optimization if the source file has the appropriate size
  77. const outputExt = getLowercaseExtension(destination)
  78. if (skipProcessing({ sourceImage, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
  79. return copy(path, destination)
  80. }
  81. await autoResize({ sourceImage, newSize, destination })
  82. }
  83. async function autoResize (options: {
  84. sourceImage: Jimp
  85. newSize: { width: number, height: number }
  86. destination: string
  87. }) {
  88. const { sourceImage, newSize, destination } = options
  89. // Portrait mode targetting a landscape, apply some effect on the image
  90. const sourceIsPortrait = sourceImage.getWidth() < sourceImage.getHeight()
  91. const destIsPortraitOrSquare = newSize.width <= newSize.height
  92. removeExif(sourceImage)
  93. if (sourceIsPortrait && !destIsPortraitOrSquare) {
  94. const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
  95. .color([ { apply: 'shade', params: [ 50 ] } ])
  96. const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
  97. return write(baseImage.blit(topImage, 0, 0), destination)
  98. }
  99. return write(sourceImage.cover(newSize.width, newSize.height), destination)
  100. }
  101. function write (image: Jimp, destination: string) {
  102. return image.quality(80).writeAsync(destination)
  103. }
  104. function skipProcessing (options: {
  105. sourceImage: Jimp
  106. newSize: { width: number, height: number }
  107. imageBytes: number
  108. inputExt: string
  109. outputExt: string
  110. }) {
  111. const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
  112. const { width, height } = newSize
  113. if (hasExif(sourceImage)) return false
  114. if (sourceImage.getWidth() > width || sourceImage.getHeight() > height) return false
  115. if (inputExt !== outputExt) return false
  116. const kB = 1000
  117. if (height >= 1000) return imageBytes <= 200 * kB
  118. if (height >= 500) return imageBytes <= 100 * kB
  119. return imageBytes <= 15 * kB
  120. }
  121. function hasExif (image: Jimp) {
  122. return !!(image.bitmap as any).exifBuffer
  123. }
  124. function removeExif (image: Jimp) {
  125. (image.bitmap as any).exifBuffer = null
  126. }