]>
Commit | Line | Data |
---|---|---|
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 | ||
6 | const Jimp = require('jimp') | |
7 | ||
8 | async function processImage ( | |
9 | path: string, | |
10 | destination: string, | |
11 | newSize: { width: number, height: number }, | |
12 | keepOriginal = false | |
13 | ) { | |
14 | const extension = extname(path) | |
15 | ||
16 | if (path === destination) { | |
17 | throw new Error('Jimp/FFmpeg needs an input path different that the output path.') | |
18 | } | |
19 | ||
20 | logger.debug('Processing image %s to %s.', path, destination) | |
21 | ||
22 | // Use FFmpeg to process GIF | |
23 | if (extension === '.gif') { | |
24 | await processGIF(path, destination, newSize) | |
25 | } else { | |
26 | await jimpProcessor(path, destination, newSize) | |
27 | } | |
28 | ||
29 | if (keepOriginal !== true) await remove(path) | |
30 | } | |
31 | ||
32 | // --------------------------------------------------------------------------- | |
33 | ||
34 | export { | |
35 | processImage | |
36 | } | |
37 | ||
38 | // --------------------------------------------------------------------------- | |
39 | ||
40 | async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }) { | |
41 | let jimpInstance: any | |
42 | ||
43 | try { | |
44 | jimpInstance = await Jimp.read(path) | |
45 | } catch (err) { | |
46 | logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err }) | |
47 | ||
48 | const newName = path + '.jpg' | |
49 | await convertWebPToJPG(path, newName) | |
50 | await rename(newName, path) | |
51 | ||
52 | jimpInstance = await Jimp.read(path) | |
53 | } | |
54 | ||
55 | await remove(destination) | |
56 | ||
57 | await jimpInstance | |
58 | .resize(newSize.width, newSize.height) | |
59 | .quality(80) | |
60 | .writeAsync(destination) | |
61 | } |