-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompressAlgorithm.js
33 lines (30 loc) · 952 Bytes
/
compressAlgorithm.js
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
import imagemin from 'imagemin';
import mozjpeg from 'imagemin-mozjpeg';
import sharp from 'sharp';
import isJpg from 'is-jpg';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const convertToJpg = async (image) => {
if (isJpg(image)) {
return image;
}
return sharp(image).jpeg().toBuffer();
}
const uploadCompressedImage = async (buffer, fileName) => {
const outputDirectory = path.join(__dirname, './output');
const miniBuffer = await imagemin.buffer(buffer, {
plugins: [convertToJpg, mozjpeg({ quality: 20 })]
});
fs.writeFileSync(`${outputDirectory}/${fileName}.jpg`, miniBuffer)
}
export const compressImage = async (image, fileName) => {
console.log(`Compressing ${fileName}...`)
if (!image) {
console.log('null')
return null;
}
await uploadCompressedImage(image, fileName);
}