image-utils.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { remove, rename } from 'fs-extra'
  2. import { extname } from 'path'
  3. import { convertWebPToJPG, processGIF } from './ffmpeg-utils'
  4. import { logger } from './logger'
  5. const Jimp = require('jimp')
  6. async function processImage (
  7. path: string,
  8. destination: string,
  9. newSize: { width: number, height: number },
  10. keepOriginal = false
  11. ) {
  12. const extension = extname(path)
  13. if (path === destination) {
  14. throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
  15. }
  16. logger.debug('Processing image %s to %s.', path, destination)
  17. // Use FFmpeg to process GIF
  18. if (extension === '.gif') {
  19. await processGIF(path, destination, newSize)
  20. } else {
  21. await jimpProcessor(path, destination, newSize)
  22. }
  23. if (keepOriginal !== true) await remove(path)
  24. }
  25. // ---------------------------------------------------------------------------
  26. export {
  27. processImage
  28. }
  29. // ---------------------------------------------------------------------------
  30. async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }) {
  31. let jimpInstance: any
  32. try {
  33. jimpInstance = await Jimp.read(path)
  34. } catch (err) {
  35. logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
  36. const newName = path + '.jpg'
  37. await convertWebPToJPG(path, newName)
  38. await rename(newName, path)
  39. jimpInstance = await Jimp.read(path)
  40. }
  41. await remove(destination)
  42. await jimpInstance
  43. .resize(newSize.width, newSize.height)
  44. .quality(80)
  45. .writeAsync(destination)
  46. }