aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/image-utils.ts
blob: da3285b13da7c3cfc902abfcfeab2f46564ab913 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import 'multer'
import * as sharp from 'sharp'
import { move, remove } from 'fs-extra'

async function processImage (
  physicalFile: { path: string },
  destination: string,
  newSize: { width: number, height: number }
) {
  if (physicalFile.path === destination) {
    throw new Error('Sharp needs an input path different that the output path.')
  }

  const sharpInstance = sharp(physicalFile.path)
  const metadata = await sharpInstance.metadata()

  // No need to resize
  if (metadata.width === newSize.width && metadata.height === newSize.height) {
    await move(physicalFile.path, destination, { overwrite: true })
    return
  }

  await remove(destination)

  await sharpInstance
    .resize(newSize.width, newSize.height)
    .toFile(destination)

  await remove(physicalFile.path)
}

// ---------------------------------------------------------------------------

export {
  processImage
}