]>
Commit | Line | Data |
---|---|---|
ac81d1a0 C |
1 | import 'multer' |
2 | import * as sharp from 'sharp' | |
a8a63227 | 3 | import { move, remove } from 'fs-extra' |
ac81d1a0 C |
4 | |
5 | async 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 | ||
34 | export { | |
35 | processImage | |
36 | } |