-
Notifications
You must be signed in to change notification settings - Fork 4
/
resize.mjs
113 lines (100 loc) · 2.91 KB
/
resize.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { ImagePool } from "@squoosh/lib";
import { cpus } from "os";
import { existsSync, readdirSync, readFileSync, mkdirSync } from "fs";
import { writeFile } from "fs/promises";
const imagePool = new ImagePool(cpus().length);
/**
* 画像フォルダのパス。今回はこのフォルダ内の画像を対象とする
*/
const IMAGE_DIR = "./images";
/**
* 出力先フォルダ
*/
const OUTPUT_DIR = "./dist";
// JPGの圧縮オプション
const jpgEncodeOptions = {
mozjpeg: { quality: 75 },
};
// PNGの圧縮オプション
const pngEncodeOptions = {
oxipng: {
effort: 2,
},
};
// 前処理(リサイズなど)のオプション
const preprocessOptions = {
// リサイズのオプション。heightまたwidthを指定しない場合は比率を維持
resize: {
enabled: true,
// 横
width: 400,
// 縦
// height: 300,
// 画像サンプリング手法 lanczos3, mitchell, catrom, triangleの4つがある。デフォルトはlanczos3
// method: "mitchell",
},
// 減色処理
// quant: {
// // 色数。最大256
// numColors: 4,
// // ディザ。0〜1で設定
// dither: 0.9,
// },
};
// 画像フォルダ内の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((fileName) => {
const imageFile = readFileSync(`${IMAGE_DIR}/${fileName}`);
const image = imagePool.ingestImage(imageFile);
return { name: fileName, image };
});
// 前処理を実行
await Promise.all(
imagePoolList.map(async (item) => {
const { image } = item;
// リサイズなどを処理するためにデコードする
await image.decoded;
return await image.preprocess(preprocessOptions);
})
);
// JPGならMozJPEGをに、PNGならOxiPNGに圧縮する
await Promise.all(
imagePoolList.map(async (item) => {
const { image } = item;
if (/\.(jpe?g)$/i.test(item.name)) {
await image.encode(jpgEncodeOptions);
}
if (/\.(png)$/i.test(item.name)) {
await image.encode(pngEncodeOptions);
}
})
);
// 圧縮したデータを出力する
for (const item of imagePoolList) {
const {
name,
image: { encodedWith },
} = item;
// 圧縮したデータを格納する変数
let data;
// JPGならMozJPEGで圧縮したデータを取得
if (encodedWith.mozjpeg) {
data = await encodedWith.mozjpeg;
}
// PNGならOxiPNGで圧縮したデータを取得
if (encodedWith.oxipng) {
data = await encodedWith.oxipng;
}
// 出力先フォルダがなければ作成
if (!existsSync(OUTPUT_DIR)) {
mkdirSync(OUTPUT_DIR);
}
// ファイルを書き込む
await writeFile(`${OUTPUT_DIR}/resised_${name}`, data.binary);
}
// imagePoolを閉じる
await imagePool.close();