-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage-processor.js
More file actions
181 lines (159 loc) · 4.89 KB
/
image-processor.js
File metadata and controls
181 lines (159 loc) · 4.89 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { mkdir, stat, rm } from "fs/promises";
import path from "path";
import colors from "ansi-colors";
import logger from "fancy-log";
import globule from "globule";
import sharp from "sharp";
class ImageProcessor {
static #DEFAULT_CONFIG = {
sourceDirectory: "src",
outputDirectory: "dist",
filenameSuffix: "",
resizeConfig: {
width: 3840,
height: 3840,
fit: "inside",
position: "center",
withoutEnlargement: true,
},
conversionFormats: {
png: {
webp: { quality: 80 },
// avif: { quality: 60 },
},
jpg: {
webp: { quality: 80 },
// avif: { quality: 60 },
},
jpeg: {
webp: { quality: 80 },
// avif: { quality: 60 },
},
webp: {
webp: { quality: 80 },
// avif: { quality: 60 },
},
avif: {
webp: { quality: 80 },
// avif: { quality: 60 },
},
},
};
#config;
constructor(config) {
this.#config = config;
}
static async create(customConfig = {}) {
const config = {
...ImageProcessor.#DEFAULT_CONFIG,
...customConfig,
};
await rm(config.outputDirectory, { recursive: true, force: true }).catch(
() => {}
);
const processor = new ImageProcessor(config);
await processor.#initialize();
return processor;
}
async #initialize() {
const targetImages = this.#findTargetImages();
const promises = [];
for (const sourcePath of targetImages) {
const imageInfo = this.#parseImagePath(sourcePath);
if (!imageInfo) {
logger(colors.red(`無効な画像パス: ${sourcePath}`));
continue;
}
const formatSettings =
this.#config.conversionFormats[imageInfo.extension];
if (!formatSettings) continue;
for (const [format, settings] of Object.entries(formatSettings)) {
promises.push(this.#convertToFormat(sourcePath, format, settings));
}
}
await Promise.all(promises);
}
#findTargetImages() {
const extensions = Object.keys(this.#config.conversionFormats);
const pattern = `/**/*.{${extensions.join(",")}}`;
const searchPath = `${this.#config.sourceDirectory}${pattern}`;
return globule.find(searchPath);
}
async #convertToFormat(sourcePath, targetFormat, settings) {
const outputPath = this.#createOutputPath(sourcePath, targetFormat);
const outputDir = path.dirname(outputPath);
await this.#ensureDirectory(outputDir);
const originalSize = (await stat(sourcePath)).size;
try {
const processor = sharp(sourcePath);
if (typeof processor.keepIccProfile === "function") {
processor.keepIccProfile();
}
if (this.#config.resizeConfig) {
processor.resize(this.#config.resizeConfig);
}
await processor.toFormat(targetFormat, settings).toFile(outputPath);
const convertedSize = (await stat(outputPath)).size;
const compressionRatio = (1 - convertedSize / originalSize) * 100;
logger(
`✓ ${colors.blue(sourcePath)} を ` +
`${colors.yellow(targetFormat.toUpperCase())} 形式に変換: ` +
`${colors.green(outputPath)} ` +
`(圧縮率: ${colors.cyan(compressionRatio.toFixed(1))}%)`
);
return {
sourcePath,
outputPath,
originalSize,
convertedSize,
compressionRatio,
format: targetFormat,
};
} catch (error) {
const errorMessage = `${colors.yellow(
targetFormat.toUpperCase()
)} 形式への変換失敗\n${error}`;
logger(colors.red(errorMessage));
throw error;
}
}
#createOutputPath(sourcePath, newFormat) {
const relative = path.relative(this.#config.sourceDirectory, sourcePath);
const basename = path.basename(relative, path.extname(relative));
const dirname = path.dirname(relative);
const suffix = this.#config.filenameSuffix || "";
return path.join(
this.#config.outputDirectory,
dirname,
`${basename}${suffix}.${newFormat}`
);
}
async #ensureDirectory(dirPath) {
try {
await mkdir(dirPath, { recursive: true });
logger(`📁 出力ディレクトリを作成: ${colors.green(dirPath)}`);
} catch (error) {
logger(colors.red(`ディレクトリ作成失敗: ${dirPath}\n${error}`));
throw error;
}
}
#parseImagePath(imagePath) {
const extensions = Object.keys(this.#config.conversionFormats).map((e) =>
e.toLowerCase()
);
const ext = path.extname(imagePath).slice(1).toLowerCase();
if (!extensions.includes(ext)) return null;
const name = path.basename(imagePath, path.extname(imagePath));
return { name, extension: ext };
}
}
export default ImageProcessor;
(async () => {
try {
await ImageProcessor.create();
} catch (err) {
logger(colors.red("画像処理で致命的なエラーが発生しました"));
logger(err);
process.exit(1);
}
})();