]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/image-utils.ts
Optimize image resizing
[github/Chocobozzz/PeerTube.git] / server / helpers / image-utils.ts
... / ...
CommitLineData
1import 'multer'
2import * as sharp from 'sharp'
3import { move, remove } from 'fs-extra'
4
5async function processImage (
6 physicalFile: { path: string },
7 destination: string,
8 newSize: { width: number, height: number }
9) {
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
26 .resize(newSize.width, newSize.height)
27 .toFile(destination)
28
29 await remove(physicalFile.path)
30}
31
32// ---------------------------------------------------------------------------
33
34export {
35 processImage
36}