]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/image-utils.ts
Allow to specify transcoding and import jobs concurrency
[github/Chocobozzz/PeerTube.git] / server / helpers / image-utils.ts
CommitLineData
18782242 1import { remove, rename } from 'fs-extra'
f619de0e 2import { extname } from 'path'
123f6193 3import { convertWebPToJPG, processGIF } from './ffmpeg-utils'
74577825 4import { logger } from './logger'
18782242 5
e6dfa586 6const Jimp = require('jimp')
ac81d1a0
C
7
8async function processImage (
2fb5b3a5 9 path: string,
ac81d1a0 10 destination: string,
e8bafea3
C
11 newSize: { width: number, height: number },
12 keepOriginal = false
ac81d1a0 13) {
123f6193
K
14 const extension = extname(path)
15
f619de0e
C
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
123f6193
K
22 // Use FFmpeg to process GIF
23 if (extension === '.gif') {
f619de0e
C
24 await processGIF(path, destination, newSize)
25 } else {
26 await jimpProcessor(path, destination, newSize)
123f6193
K
27 }
28
f619de0e
C
29 if (keepOriginal !== true) await remove(path)
30}
a8a63227 31
f619de0e 32// ---------------------------------------------------------------------------
a8a63227 33
f619de0e
C
34export {
35 processImage
36}
37
38// ---------------------------------------------------------------------------
39
40async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }) {
18782242
C
41 let jimpInstance: any
42
43 try {
44 jimpInstance = await Jimp.read(path)
45 } catch (err) {
b5b68755 46 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
18782242
C
47
48 const newName = path + '.jpg'
49 await convertWebPToJPG(path, newName)
50 await rename(newName, path)
51
52 jimpInstance = await Jimp.read(path)
53 }
a8a63227
C
54
55 await remove(destination)
56
e6dfa586 57 await jimpInstance
ac81d1a0 58 .resize(newSize.width, newSize.height)
e6dfa586
RK
59 .quality(80)
60 .writeAsync(destination)
ac81d1a0 61}