MCPcopy Create free account
hub / github.com/Silentely/eSIM-Tools / optimizeImage

Function optimizeImage

scripts/optimize-images.js:43–104  ·  view source on GitHub ↗
(inputPath, outputPath, format, options = {})

Source from the content-addressed store, hash-verified

41
42// 优化单个图片
43async function optimizeImage(inputPath, outputPath, format, options = {}) {
44 try {
45 // Check if output already exists and is newer than input
46 if (fs.existsSync(outputPath)) {
47 const inputStats = await stat(inputPath);
48 const outputStats = await stat(outputPath);
49 if (outputStats.mtime > inputStats.mtime) {
50 BuildLogger.log(`⏭️ 跳过已优化: ${path.basename(outputPath)}`);
51 return true;
52 }
53 }
54
55 const image = sharp(inputPath);
56
57 // Get image metadata for size validation
58 const metadata = await image.metadata();
59
60 // Apply format-specific optimizations
61 switch (format) {
62 case 'jpeg':
63 await image
64 .jpeg({
65 quality: options.quality || config.formats.jpeg.quality,
66 progressive: true,
67 mozjpeg: true // Use mozjpeg for better compression
68 })
69 .toFile(outputPath);
70 break;
71 case 'png':
72 await image
73 .png({
74 compressionLevel: 9,
75 progressive: true,
76 adaptiveFiltering: true
77 })
78 .toFile(outputPath);
79 break;
80 case 'webp':
81 await image
82 .webp({
83 quality: options.quality || config.formats.webp.quality,
84 effort: 6,
85 smartSubsample: true
86 })
87 .toFile(outputPath);
88 break;
89 default:
90 await image.toFile(outputPath);
91 }
92
93 // Calculate compression savings
94 const inputSize = (await stat(inputPath)).size;
95 const outputSize = (await stat(outputPath)).size;
96 const savings = ((inputSize - outputSize) / inputSize * 100).toFixed(1);
97
98 BuildLogger.success(' 优化完成: ${path.basename(inputPath)} -> ${format.toUpperCase()} (节省 ${savings}%)');
99 return { success: true, inputSize, outputSize, savings };
100 } catch (error) {

Callers 1

generateMultipleFormatsFunction · 0.85

Calls 3

logMethod · 0.45
successMethod · 0.45
errorMethod · 0.45

Tested by

no test coverage detected