]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/image-utils.ts
fdf06e848b86a294fa662d23751c699b519260c1
[github/Chocobozzz/PeerTube.git] / server / helpers / image-utils.ts
1 import { extname } from 'path'
2 import { remove, rename } from 'fs-extra'
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 // Use FFmpeg to process GIF
17 if (extension === '.gif') {
18 return processGIF(path, destination, newSize, keepOriginal)
19 }
20
21 if (path === destination) {
22 throw new Error('Jimp needs an input path different that the output path.')
23 }
24
25 logger.debug('Processing image %s to %s.', path, destination)
26
27 let jimpInstance: any
28
29 try {
30 jimpInstance = await Jimp.read(path)
31 } catch (err) {
32 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
33
34 const newName = path + '.jpg'
35 await convertWebPToJPG(path, newName)
36 await rename(newName, path)
37
38 jimpInstance = await Jimp.read(path)
39 }
40
41 await remove(destination)
42
43 await jimpInstance
44 .resize(newSize.width, newSize.height)
45 .quality(80)
46 .writeAsync(destination)
47
48 if (keepOriginal !== true) await remove(path)
49 }
50
51 // ---------------------------------------------------------------------------
52
53 export {
54 processImage
55 }