-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathcompress-images.js
More file actions
122 lines (105 loc) · 3.58 KB
/
compress-images.js
File metadata and controls
122 lines (105 loc) · 3.58 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
/**
* Image Compression Script using Sharp
*
* Features:
* - Validates input image existence
* - Ensures output directories exist
* - Uses correct, format-specific compression options
* - Strips metadata by default (Sharp behavior)
* - Processes images in parallel for better performance
*/
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
/**
* List of images to be compressed
* Add or remove paths as needed
*/
const images = [
'assets/demo.png',
'assets/host-event.jpg',
'assets/logo.png'
];
/**
* Compress a single image based on its file type
*
* @param {string} inputPath - Path to the source image
* @returns {Promise<void>}
*/
async function compressImage(inputPath) {
/* ---------------------------------------------------
* 1. Validate input file existence
* --------------------------------------------------- */
if (!fs.existsSync(inputPath)) {
throw new Error(`Input file does not exist: ${inputPath}`);
}
/* ---------------------------------------------------
* 2. Resolve paths and extensions
* --------------------------------------------------- */
const ext = path.extname(inputPath).toLowerCase();
const outputPath = inputPath.replace(ext, `_compressed${ext}`);
const outputDir = path.dirname(outputPath);
/* ---------------------------------------------------
* 3. Ensure output directory exists
* --------------------------------------------------- */
fs.mkdirSync(outputDir, { recursive: true });
/* ---------------------------------------------------
* 4. Initialize Sharp pipeline
* (metadata is stripped by default)
* --------------------------------------------------- */
let pipeline = sharp(inputPath);
/* ---------------------------------------------------
* 4.1 Safeguard against very large images
* --------------------------------------------------- */
const metadata = await pipeline.metadata();
const MAX_PIXELS = 12_000_000;
if (metadata.width * metadata.height > MAX_PIXELS) {
throw new Error(
`Image too large to safely process: ${metadata.width}×${metadata.height}`
);
}
/* ---------------------------------------------------
* 5. Apply format-specific compression
* --------------------------------------------------- */
if (ext === '.png') {
// PNG: lossless compression
// Apply palette quantization only when safe to avoid banding
const usePalette =
!metadata.hasAlpha &&
metadata.width * metadata.height < 3_000_000;
pipeline = pipeline.png({
compressionLevel: 9,
palette: usePalette
});
} else if (ext === '.jpg' || ext === '.jpeg') {
// JPEG: optimized, progressive encoding for better web loading
pipeline = pipeline.jpeg({
quality: 80,
mozjpeg: true,
progressive: true
});
} else {
throw new Error(`Unsupported file type: ${ext}`);
}
/* ---------------------------------------------------
* 6. Write compressed image to disk
* --------------------------------------------------- */
await pipeline.toFile(outputPath);
console.log(`✔ Compressed: ${inputPath} → ${outputPath}`);
}
/**
* Main entry point
* Compresses all images in parallel
*/
async function main() {
try {
await Promise.all(
images.map(image => compressImage(image))
);
console.log('✅ Image compression completed.');
} catch (error) {
console.error('❌ Compression failed:', error.message);
}
}
// Execute script
main();