-
Notifications
You must be signed in to change notification settings - Fork 4
/
convert.mjs
65 lines (56 loc) · 1.72 KB
/
convert.mjs
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
65
import { ImagePool } from "@squoosh/lib";
import { cpus } from "os";
import { existsSync, readdirSync, readFileSync, mkdirSync } from "fs";
import { writeFile } from "fs/promises";
import path from "path";
const imagePool = new ImagePool(cpus().length);
/**
* 画像フォルダのパス。今回はこのフォルダ内の画像を対象とする
*/
const IMAGE_DIR = "./images";
/**
* 出力先フォルダ
*/
const OUTPUT_DIR = "./dist";
// WebPの圧縮オプション
const webpEncodeOptions = {
webp: {
quality: 75,
},
};
// 画像フォルダ内のJPGとPNGを抽出
const imageFileList = readdirSync(IMAGE_DIR).filter((file) => {
const regex = /\.(jpe?g|png)$/i;
return regex.test(file);
});
// 抽出したファイルをimagePool内にセットし、ファイル名とimagePoolの配列を作成
const imagePoolList = imageFileList.map((file) => {
const imageFile = readFileSync(`${IMAGE_DIR}/${file}`);
const fileName = path.parse(`${IMAGE_DIR}/${file}`).name;
const image = imagePool.ingestImage(imageFile);
return { name: fileName, image };
});
// Webpで圧縮する
await Promise.all(
imagePoolList.map(async (item) => {
const { image } = item;
await image.encode(webpEncodeOptions);
})
);
// 圧縮したデータを出力する
for (const item of imagePoolList) {
const {
name,
image: { encodedWith },
} = item;
// WebPで圧縮したデータを取得
const data = await encodedWith.webp;
// 出力先フォルダがなければ作成
if (!existsSync(OUTPUT_DIR)) {
mkdirSync(OUTPUT_DIR);
}
// 拡張子をwebpに変換してファイルを書き込む
await writeFile(`${OUTPUT_DIR}/${name}.webp`, data.binary);
}
// imagePoolを閉じる
await imagePool.close();