1 import { copy, readFile, remove, rename } from 'fs-extra'
2 import * as Jimp from 'jimp'
3 import { getLowercaseExtension } from './core-utils'
4 import { convertWebPToJPG, processGIF } from './ffmpeg-utils'
5 import { logger } from './logger'
6 import { buildUUID } from './uuid'
8 function generateImageFilename (extension = '.jpg') {
9 return buildUUID() + extension
12 async function processImage (
15 newSize: { width: number, height: number },
18 const extension = getLowercaseExtension(path)
20 if (path === destination) {
21 throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
24 logger.debug('Processing image %s to %s.', path, destination)
26 // Use FFmpeg to process GIF
27 if (extension === '.gif') {
28 await processGIF(path, destination, newSize)
30 await jimpProcessor(path, destination, newSize, extension)
33 if (keepOriginal !== true) await remove(path)
36 // ---------------------------------------------------------------------------
39 generateImageFilename,
43 // ---------------------------------------------------------------------------
45 async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
46 let jimpInstance: Jimp
47 const inputBuffer = await readFile(path)
50 jimpInstance = await Jimp.read(inputBuffer)
52 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
54 const newName = path + '.jpg'
55 await convertWebPToJPG(path, newName)
56 await rename(newName, path)
58 jimpInstance = await Jimp.read(path)
61 await remove(destination)
63 // Optimization if the source file has the appropriate size
64 const outputExt = getLowercaseExtension(destination)
65 if (skipProcessing({ jimpInstance, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
66 return copy(path, destination)
70 .resize(newSize.width, newSize.height)
72 .writeAsync(destination)
75 function skipProcessing (options: {
77 newSize: { width: number, height: number }
82 const { jimpInstance, newSize, imageBytes, inputExt, outputExt } = options
83 const { width, height } = newSize
85 if (jimpInstance.getWidth() > width || jimpInstance.getHeight() > height) return false
86 if (inputExt !== outputExt) return false
90 if (height >= 1000) return imageBytes <= 200 * kB
91 if (height >= 500) return imageBytes <= 100 * kB
93 return imageBytes <= 15 * kB