]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/image-utils.ts
Update FAQ
[github/Chocobozzz/PeerTube.git] / server / helpers / image-utils.ts
... / ...
CommitLineData
1import { remove, rename } from 'fs-extra'
2import { extname } from 'path'
3import { convertWebPToJPG, processGIF } from './ffmpeg-utils'
4import { logger } from './logger'
5
6const Jimp = require('jimp')
7
8async 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
34export {
35 processImage
36}
37
38// ---------------------------------------------------------------------------
39
40async 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}