image-utils.ts 820 B

1234567891011121314151617181920212223242526272829303132333435
  1. import 'multer'
  2. import * as sharp from 'sharp'
  3. import { readFile, remove } from 'fs-extra'
  4. import { logger } from './logger'
  5. async function processImage (
  6. path: string,
  7. destination: string,
  8. newSize: { width: number, height: number },
  9. keepOriginal = false
  10. ) {
  11. if (path === destination) {
  12. throw new Error('Sharp needs an input path different that the output path.')
  13. }
  14. logger.debug('Processing image %s to %s.', path, destination)
  15. // Avoid sharp cache
  16. const buf = await readFile(path)
  17. const sharpInstance = sharp(buf)
  18. await remove(destination)
  19. await sharpInstance
  20. .resize(newSize.width, newSize.height)
  21. .toFile(destination)
  22. if (keepOriginal !== true) await remove(path)
  23. }
  24. // ---------------------------------------------------------------------------
  25. export {
  26. processImage
  27. }