]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/image-utils.ts
Optimize image resizing
[github/Chocobozzz/PeerTube.git] / server / helpers / image-utils.ts
CommitLineData
ac81d1a0
C
1import 'multer'
2import * as sharp from 'sharp'
a8a63227 3import { move, remove } from 'fs-extra'
ac81d1a0
C
4
5async function processImage (
02988fdc 6 physicalFile: { path: string },
ac81d1a0
C
7 destination: string,
8 newSize: { width: number, height: number }
9) {
a8a63227
C
10 if (physicalFile.path === destination) {
11 throw new Error('Sharp needs an input path different that the output path.')
12 }
13
14 const sharpInstance = sharp(physicalFile.path)
15 const metadata = await sharpInstance.metadata()
16
17 // No need to resize
18 if (metadata.width === newSize.width && metadata.height === newSize.height) {
19 await move(physicalFile.path, destination, { overwrite: true })
20 return
21 }
22
23 await remove(destination)
24
25 await sharpInstance
ac81d1a0
C
26 .resize(newSize.width, newSize.height)
27 .toFile(destination)
28
62689b94 29 await remove(physicalFile.path)
ac81d1a0
C
30}
31
32// ---------------------------------------------------------------------------
33
34export {
35 processImage
36}