-
Notifications
You must be signed in to change notification settings - Fork 14
/
compressImage.js
64 lines (59 loc) · 1.5 KB
/
compressImage.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { ImagePool } from '@squoosh/lib';
import fs from 'fs';
import { promisify } from 'util';
const writeFile = promisify(fs.writeFile);
const extension = {
jpeg: "jpg",
avif: "avif",
};
const encodeOptions = {
jpeg: {
key: 'mozjpeg',
encodeOptions: {
mozjpeg: {
quality: 70,
},
},
},
avif: {
key: 'avif',
encodeOptions: {
avif: {
cqLevel: 41,
},
},
},
};
function sizedName(filename, width, format) {
const ext = extension[format];
if (!ext) {
throw new Error(`Unknown format ${format}`);
}
return filename.replace(/\.\w+$/, (_) => "-" + width + "w" + "." + ext);
}
async function resize(filename, width, format) {
const out = sizedName(filename, width, format);
if (fs.existsSync(".cache" + out)) {
return out;
}
const imagePool = new ImagePool();
const image = imagePool.ingestImage(`./src${filename}`);
await image.decoded;
await image.preprocess({
resize: {
enabled: true,
width,
},
});
const e = encodeOptions[format];
await image.encode(e.encodeOptions);
for (const encodedImage of Object.values(image.encodedWith)) {
await writeFile(
`.cache${out}`,
(await encodedImage).binary,
);
}
imagePool.close();
return out;
}
await resize(process.argv[2], parseInt(process.argv[3], 10), process.argv[4])