Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Update images with new compression tool

Richie McIlroy49d7711eb134
diff --git a/apps/web/package.json b/apps/web/package.json
index 73e193531..79be69c83 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -6,7 +6,8 @@
"dev": "dotenv -e ../../.env -- next dev",
"build": "next build",
"start": "next start",
- "lint": "next lint"
+ "lint": "next lint",
+ "compress-images": "bash tools/compress-images.sh"
},
"dependencies": {
"@aws-sdk/client-cloudfront": "^3.565.0",
diff --git a/apps/web/public/android-chrome-192x192.png b/apps/web/public/android-chrome-192x192.png
index 1dff083b3..688a16b36 100644
Binary files a/apps/web/public/android-chrome-192x192.png and b/apps/web/public/android-chrome-192x192.png differ
diff --git a/apps/web/public/android-chrome-512x512.png b/apps/web/public/android-chrome-512x512.png
index 38e137b9b..0358e1a50 100644
Binary files a/apps/web/public/android-chrome-512x512.png and b/apps/web/public/android-chrome-512x512.png differ
diff --git a/apps/web/public/blog/cap-beta-release.jpg b/apps/web/public/blog/cap-beta-release.jpg
index 94a71c4ae..5878f1a32 100644
Binary files a/apps/web/public/blog/cap-beta-release.jpg and b/apps/web/public/blog/cap-beta-release.jpg differ
diff --git a/apps/web/public/blog/og.png b/apps/web/public/blog/og.png
index 5c60da7e9..ca2b677d1 100644
Binary files a/apps/web/public/blog/og.png and b/apps/web/public/blog/og.png differ
diff --git a/apps/web/public/blog/stripe-payment-attack.jpg b/apps/web/public/blog/stripe-payment-attack.jpg
index 45160ae89..a12e16f5e 100644
Binary files a/apps/web/public/blog/stripe-payment-attack.jpg and b/apps/web/public/blog/stripe-payment-attack.jpg differ
diff --git a/apps/web/public/cap-emoji-banner.png b/apps/web/public/cap-emoji-banner.png
index 2887d2630..12b09f44b 100644
Binary files a/apps/web/public/cap-emoji-banner.png and b/apps/web/public/cap-emoji-banner.png differ
diff --git a/apps/web/public/favicon-16x16.png b/apps/web/public/favicon-16x16.png
index 0923ff00e..cf775b749 100644
Binary files a/apps/web/public/favicon-16x16.png and b/apps/web/public/favicon-16x16.png differ
diff --git a/apps/web/public/illustrations/app.webp b/apps/web/public/illustrations/app.webp
index 28d9ac9e5..d37db694b 100644
Binary files a/apps/web/public/illustrations/app.webp and b/apps/web/public/illustrations/app.webp differ
diff --git a/apps/web/public/illustrations/bottomcloud.webp b/apps/web/public/illustrations/bottomcloud.webp
index b1a504040..41e0eccbf 100644
Binary files a/apps/web/public/illustrations/bottomcloud.webp and b/apps/web/public/illustrations/bottomcloud.webp differ
diff --git a/apps/web/public/illustrations/chipcloud.webp b/apps/web/public/illustrations/chipcloud.webp
index 8f986ed12..a9e330b30 100644
Binary files a/apps/web/public/illustrations/chipcloud.webp and b/apps/web/public/illustrations/chipcloud.webp differ
diff --git a/apps/web/public/illustrations/cloud-1.png b/apps/web/public/illustrations/cloud-1.png
index 93f7d351f..4f5b4f91f 100644
Binary files a/apps/web/public/illustrations/cloud-1.png and b/apps/web/public/illustrations/cloud-1.png differ
diff --git a/apps/web/public/illustrations/cloud-2.png b/apps/web/public/illustrations/cloud-2.png
index 67acef077..e8d6a764f 100644
Binary files a/apps/web/public/illustrations/cloud-2.png and b/apps/web/public/illustrations/cloud-2.png differ
diff --git a/apps/web/public/illustrations/cloud-3.png b/apps/web/public/illustrations/cloud-3.png
index 7c04c73cd..7b5cc6df6 100644
Binary files a/apps/web/public/illustrations/cloud-3.png and b/apps/web/public/illustrations/cloud-3.png differ
diff --git a/apps/web/public/illustrations/multiplatbg.webp b/apps/web/public/illustrations/multiplatbg.webp
index 1e85663c5..a8f78bd2f 100644
Binary files a/apps/web/public/illustrations/multiplatbg.webp and b/apps/web/public/illustrations/multiplatbg.webp differ
diff --git a/apps/web/public/illustrations/multiplatmain.webp b/apps/web/public/illustrations/multiplatmain.webp
index 929379a5c..7e59effe8 100644
Binary files a/apps/web/public/illustrations/multiplatmain.webp and b/apps/web/public/illustrations/multiplatmain.webp differ
diff --git a/apps/web/public/illustrations/privacy.webp b/apps/web/public/illustrations/privacy.webp
index 048b6eb71..4038cc8c4 100644
Binary files a/apps/web/public/illustrations/privacy.webp and b/apps/web/public/illustrations/privacy.webp differ
diff --git a/apps/web/public/illustrations/smallcloud.webp b/apps/web/public/illustrations/smallcloud.webp
index 646a5fd1b..3cb5a6f75 100644
Binary files a/apps/web/public/illustrations/smallcloud.webp and b/apps/web/public/illustrations/smallcloud.webp differ
diff --git a/apps/web/public/illustrations/smallcloudthree.webp b/apps/web/public/illustrations/smallcloudthree.webp
index 54594c839..52be36556 100644
Binary files a/apps/web/public/illustrations/smallcloudthree.webp and b/apps/web/public/illustrations/smallcloudthree.webp differ
diff --git a/apps/web/public/illustrations/smallcloudtwo.webp b/apps/web/public/illustrations/smallcloudtwo.webp
index db374806b..9b67e89d3 100644
Binary files a/apps/web/public/illustrations/smallcloudtwo.webp and b/apps/web/public/illustrations/smallcloudtwo.webp differ
diff --git a/apps/web/public/illustrations/unlimitedrecordingbg.webp b/apps/web/public/illustrations/unlimitedrecordingbg.webp
index 505c0ed42..5553622b3 100644
Binary files a/apps/web/public/illustrations/unlimitedrecordingbg.webp and b/apps/web/public/illustrations/unlimitedrecordingbg.webp differ
diff --git a/apps/web/public/illustrations/video-capture.webp b/apps/web/public/illustrations/video-capture.webp
index b0d30e9e4..43dc0f2d2 100644
Binary files a/apps/web/public/illustrations/video-capture.webp and b/apps/web/public/illustrations/video-capture.webp differ
diff --git a/apps/web/public/illustrations/windows-bg.jpg b/apps/web/public/illustrations/windows-bg.jpg
index 255eed099..6cefb186d 100644
Binary files a/apps/web/public/illustrations/windows-bg.jpg and b/apps/web/public/illustrations/windows-bg.jpg differ
diff --git a/apps/web/public/landing-banner.jpg b/apps/web/public/landing-banner.jpg
index 11c3b2a01..4535404d9 100644
Binary files a/apps/web/public/landing-banner.jpg and b/apps/web/public/landing-banner.jpg differ
diff --git a/apps/web/public/logos/product-hunt.png b/apps/web/public/logos/product-hunt.png
index 1e6607ae2..85dbd0340 100644
Binary files a/apps/web/public/logos/product-hunt.png and b/apps/web/public/logos/product-hunt.png differ
diff --git a/apps/web/tools/compress-images.js b/apps/web/tools/compress-images.js
new file mode 100644
index 000000000..caefc88fe
--- /dev/null
+++ b/apps/web/tools/compress-images.js
@@ -0,0 +1,258 @@
+#!/usr/bin/env node
+
+/**
+ * Image Compression Tool
+ *
+ * This script automatically compresses JPG, PNG, and WebP images in the public directory
+ * to reduce file sizes while maintaining acceptable quality. It creates a temporary
+ * directory with compressed versions, shows compression statistics, and optionally
+ * replaces the original files with optimized versions.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { execSync } = require('child_process');
+const readline = require('readline');
+const os = require('os');
+const crypto = require('crypto');
+
+// Create a unique temporary directory for installation
+function createTempInstallDir() {
+ const tmpDir = path.join(os.tmpdir(), `image-compressor-${crypto.randomBytes(6).toString('hex')}`);
+ fs.mkdirSync(tmpDir, { recursive: true });
+ return tmpDir;
+}
+
+// Check and load dependencies from a clean temporary directory
+function loadDependencies() {
+ const requiredDeps = ['sharp', 'glob', 'chalk'];
+ let tempDir = null;
+
+ try {
+ // Try to require the dependencies directly
+ const sharp = require('sharp');
+ const glob = require('glob');
+ const chalk = require('chalk');
+
+ return { sharp, glob, chalk };
+ } catch (e) {
+ // If dependencies are missing, install them in a temporary directory
+ console.log(`Required dependencies not found. Installing temporarily...`);
+
+ tempDir = createTempInstallDir();
+ const packageJson = path.join(tempDir, 'package.json');
+
+ // Create a minimal package.json
+ fs.writeFileSync(packageJson, JSON.stringify({
+ name: "image-compressor-temp",
+ version: "1.0.0",
+ private: true,
+ dependencies: {}
+ }));
+
+ try {
+ // Install dependencies in the temporary directory
+ execSync(`npm install ${requiredDeps.join(' ')}`, {
+ cwd: tempDir,
+ stdio: 'inherit'
+ });
+
+ // Create a simple loader script
+ const loaderScript = path.join(tempDir, 'load-deps.js');
+ fs.writeFileSync(loaderScript, `
+ exports.sharp = require('sharp');
+ exports.glob = require('glob');
+ exports.chalk = require('chalk');
+ `);
+
+ // Load dependencies from the temporary installation
+ return require(loaderScript);
+ } catch (error) {
+ console.error(`Failed to install dependencies: ${error.message}`);
+ console.error('Please install these packages globally and try again:');
+ console.error(`npm install -g sharp glob chalk`);
+
+ if (tempDir && fs.existsSync(tempDir)) {
+ try { fs.rmSync(tempDir, { recursive: true }); } catch (e) {}
+ }
+
+ process.exit(1);
+ }
+ }
+}
+
+// Create readline interface for user input
+function createInterface() {
+ return readline.createInterface({
+ input: process.stdin,
+ output: process.stdout
+ });
+}
+
+// Ask user for confirmation
+async function askForConfirmation(question) {
+ const rl = createInterface();
+
+ return new Promise((resolve) => {
+ rl.question(question + ' (y/n): ', (answer) => {
+ rl.close();
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
+ });
+ });
+}
+
+// Main function
+async function main() {
+ // Load dependencies
+ console.log('Preparing image compression tool...');
+ const { sharp, glob, chalk } = loadDependencies();
+
+ // Force apply mode without asking (for script compatibility)
+ const forceApply = process.argv.includes('--apply');
+
+ const publicDir = path.join(__dirname, '../public');
+ const compressedDir = path.join(__dirname, '../public-compressed');
+
+ console.log(chalk.blue('πŸ” Scanning for images in public folder...'));
+
+ // Create compressed directory if it doesn't exist
+ if (!fs.existsSync(compressedDir)) {
+ fs.mkdirSync(compressedDir, { recursive: true });
+ }
+
+ // Find all images in public folder
+ const imageTypes = ['jpeg', 'jpg', 'png', 'webp'];
+ const imagePatterns = imageTypes.map(type => `${publicDir}/**/*.${type}`);
+
+ let images = [];
+ imagePatterns.forEach(pattern => {
+ const matches = glob.sync(pattern, { nocase: true });
+ images = [...images, ...matches];
+ });
+
+ if (images.length === 0) {
+ console.log(chalk.yellow('No images found in the public directory.'));
+ process.exit(0);
+ }
+
+ console.log(chalk.green(`πŸ“· Found ${images.length} images to compress\n`));
+
+ // Process each image
+ const totalSize = { original: 0, compressed: 0 };
+ const failedImages = [];
+
+ // Use a progress indicator
+ let processedCount = 0;
+
+ console.log(chalk.blue('πŸ”„ Starting compression process...'));
+
+ for (const imagePath of images) {
+ const relativePath = path.relative(publicDir, imagePath);
+ const outputPath = path.join(compressedDir, relativePath);
+ const outputDir = path.dirname(outputPath);
+
+ processedCount++;
+ const percentage = Math.floor((processedCount / images.length) * 100);
+ process.stdout.write(`\r${chalk.blue('⏳ Progress:')} ${chalk.yellow(`${percentage}%`)} - Processing image ${processedCount}/${images.length}`);
+
+ // Create output directory if it doesn't exist
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
+ // Get original file size
+ const stats = fs.statSync(imagePath);
+ totalSize.original += stats.size;
+
+ // Get image extension
+ const ext = path.extname(imagePath).toLowerCase();
+
+ try {
+ let sharpImage = sharp(imagePath);
+
+ // Apply appropriate compression based on file type
+ if (ext === '.jpg' || ext === '.jpeg') {
+ sharpImage = sharpImage.jpeg({ quality: 75, mozjpeg: true });
+ } else if (ext === '.png') {
+ sharpImage = sharpImage.png({ compressionLevel: 6, adaptiveFiltering: true });
+ } else if (ext === '.webp') {
+ sharpImage = sharpImage.webp({ quality: 75 });
+ }
+
+ // Save compressed image
+ await sharpImage.toFile(outputPath);
+
+ // Get compressed file size
+ const compressedStats = fs.statSync(outputPath);
+ totalSize.compressed += compressedStats.size;
+ } catch (error) {
+ failedImages.push({ path: relativePath, error: error.message });
+ }
+ }
+
+ // Clear the progress line
+ process.stdout.write('\r' + ' '.repeat(100) + '\r');
+
+ // Calculate total savings
+ const totalSavingsMB = ((totalSize.original - totalSize.compressed) / (1024 * 1024)).toFixed(2);
+ const totalSavingsPercent = ((totalSize.original - totalSize.compressed) / totalSize.original * 100).toFixed(2);
+
+ console.log('\n\n' + chalk.blue('πŸ“Š ===== Compression Summary ====='));
+ console.log(chalk.blue(`πŸ“¦ Original Size: ${chalk.yellow((totalSize.original / (1024 * 1024)).toFixed(2) + ' MB')}`));
+ console.log(chalk.blue(`πŸ“¦ Compressed Size: ${chalk.yellow((totalSize.compressed / (1024 * 1024)).toFixed(2) + ' MB')}`));
+ console.log(chalk.blue(`πŸ’° Saved: ${chalk.green(totalSavingsMB + ' MB')} (${chalk.green(totalSavingsPercent + '%')})`) + '\n');
+
+ if (failedImages.length > 0) {
+ console.log(chalk.red(`❌ Failed to compress ${failedImages.length} images:`));
+ failedImages.forEach(img => {
+ console.log(chalk.red(` - ${img.path}: ${img.error}`));
+ });
+ console.log('');
+ }
+
+ console.log(chalk.blue(`πŸ” Compressed images are available in: ${chalk.yellow(compressedDir)}`));
+ console.log(chalk.blue(' You can compare the quality before applying changes.') + '\n');
+
+ // Ask for confirmation or use force apply
+ let shouldApply = forceApply;
+
+ if (!forceApply) {
+ shouldApply = await askForConfirmation(chalk.yellow('Do you want to replace the original images with the compressed versions?'));
+ }
+
+ if (shouldApply) {
+ console.log(chalk.blue('\nπŸ”„ Replacing original images with compressed versions...'));
+
+ let replacedCount = 0;
+ for (const imagePath of images) {
+ const relativePath = path.relative(publicDir, imagePath);
+ const compressedPath = path.join(compressedDir, relativePath);
+
+ if (fs.existsSync(compressedPath)) {
+ fs.copyFileSync(compressedPath, imagePath);
+ replacedCount++;
+
+ const percentage = Math.floor((replacedCount / images.length) * 100);
+ process.stdout.write(`\r${chalk.blue('⏳ Progress:')} ${chalk.yellow(`${percentage}%`)} - Replacing image ${replacedCount}/${images.length}`);
+ }
+ }
+
+ // Clear the progress line
+ process.stdout.write('\r' + ' '.repeat(100) + '\r');
+
+ // Remove compressed directory
+ fs.rmSync(compressedDir, { recursive: true, force: true });
+ console.log(chalk.green(`\nβœ… Success! All ${replacedCount} images have been optimized and replaced.`));
+ console.log(chalk.green(`🧹 Temporary compressed folder has been removed.`));
+ } else {
+ console.log(chalk.blue('\nπŸ‘€ No changes applied. You can:'));
+ console.log(chalk.blue(` 1. View the compressed images in ${chalk.yellow(compressedDir)}`));
+ console.log(chalk.blue(' 2. Run this tool again if you decide to apply changes'));
+ console.log(chalk.blue(' 3. Or manually replace images you want to use') + '\n');
+ }
+}
+
+main().catch(err => {
+ console.error('Error during image compression:', err);
+ process.exit(1);
+});
\ No newline at end of file
diff --git a/apps/web/tools/compress-images.sh b/apps/web/tools/compress-images.sh
new file mode 100755
index 000000000..e732d0b24
--- /dev/null
+++ b/apps/web/tools/compress-images.sh
@@ -0,0 +1,399 @@
+#!/bin/bash
+
+# Image Compression Shell Script Wrapper
+#
+# This script creates a temporary environment with Node.js dependencies for image compression,
+# generates a Node.js script that handles the actual compression logic, and runs it within
+# the temporary environment. It handles setup, dependency installation, and cleanup automatically.
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+BLUE='\033[0;34m'
+YELLOW='\033[0;33m'
+NC='\033[0m'
+
+echo -e "${BLUE}πŸ“¦ Cap Image Compression Tool${NC}"
+echo -e "${BLUE}---------------------------${NC}\n"
+
+PROJECT_ROOT=$(cd "$(dirname "$0")/.." && pwd)
+echo -e "${BLUE}Project root: ${YELLOW}${PROJECT_ROOT}${NC}"
+
+TEMP_DIR=$(mktemp -d)
+cd "$TEMP_DIR"
+
+cat > package.json << EOF
+{
+ "name": "image-compressor-temp",
+ "version": "1.0.0",
+ "private": true,
+ "dependencies": {
+ "sharp": "^0.33.2",
+ "glob": "^10.3.10",
+ "chalk": "^4.1.2"
+ }
+}
+EOF
+
+cat > compress-images.js << 'EOL'
+const fs = require('fs');
+const path = require('path');
+const readline = require('readline');
+
+try {
+ var sharp = require('sharp');
+ var glob = require('glob');
+ var chalk = require('chalk');
+} catch (error) {
+ console.error('Error loading dependencies:', error.message);
+ console.error('Please run "npm install" in the temporary directory before running this script.');
+ process.exit(1);
+}
+
+function createInterface() {
+ return readline.createInterface({
+ input: process.stdin,
+ output: process.stdout
+ });
+}
+
+async function askForConfirmation(question) {
+ const rl = createInterface();
+
+ return new Promise((resolve) => {
+ rl.question(question + ' (y/n): ', (answer) => {
+ rl.close();
+ resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
+ });
+ });
+}
+
+function formatBytes(bytes, decimals = 2) {
+ if (bytes === 0) return '0 Bytes';
+
+ const k = 1024;
+ const dm = decimals < 0 ? 0 : decimals;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
+}
+
+function checkDirectoryForImages(dir, types) {
+ if (!fs.existsSync(dir)) {
+ console.log(chalk.red(`Directory does not exist: ${dir}`));
+ return false;
+ }
+
+ console.log(chalk.blue(`Checking directory: ${dir}`));
+ try {
+ const allFiles = fs.readdirSync(dir, { recursive: true });
+ console.log(chalk.yellow(`Total files found: ${allFiles.length}`));
+
+ const imageFiles = allFiles.filter(file => {
+ const ext = path.extname(file).toLowerCase();
+ return types.includes(ext.replace('.', ''));
+ });
+
+ console.log(chalk.yellow(`Image files found: ${imageFiles.length}`));
+ return imageFiles.length > 0;
+ } catch (err) {
+ console.log(chalk.red(`Error reading directory: ${err.message}`));
+ return false;
+ }
+}
+
+async function main() {
+ const forceApply = process.argv.includes('--apply');
+ const detailedOutput = !process.argv.includes('--quiet');
+
+ const scriptDir = process.env.PROJECT_ROOT;
+ console.log(chalk.blue(`Project root from environment: ${scriptDir}`));
+
+ const possiblePublicDirs = [
+ path.join(scriptDir, 'public'),
+ path.join(scriptDir, 'static'),
+ scriptDir,
+ path.join(scriptDir, '..', 'public')
+ ];
+
+ let publicDir = null;
+ const imageExtensions = ['jpeg', 'jpg', 'png', 'webp'];
+
+ for (const dir of possiblePublicDirs) {
+ console.log(chalk.blue(`Checking potential public directory: ${dir}`));
+ if (fs.existsSync(dir)) {
+ publicDir = dir;
+ break;
+ }
+ }
+
+ if (!publicDir) {
+ console.log(chalk.red('Could not find a valid public directory!'));
+ process.exit(1);
+ }
+
+ console.log(chalk.green(`Using public directory: ${publicDir}`));
+
+ const compressedDir = path.join(scriptDir, 'public-compressed');
+
+ console.log(chalk.blue('πŸ” Scanning for images in public folder...'));
+
+ if (fs.existsSync(compressedDir)) {
+ console.log(chalk.yellow('Removing existing compressed folder...'));
+ fs.rmSync(compressedDir, { recursive: true, force: true });
+ }
+
+ fs.mkdirSync(compressedDir, { recursive: true });
+
+ if (!checkDirectoryForImages(publicDir, imageExtensions)) {
+ console.log(chalk.yellow(`\nNo images found in ${publicDir}.`));
+ console.log(chalk.yellow('Please check if this is the correct directory for your images.'));
+
+ const shouldContinue = await askForConfirmation(chalk.blue('Do you want to manually specify a different directory?'));
+
+ if (shouldContinue) {
+ console.log(chalk.blue('\nPlease run the script again with the correct path.'));
+ process.exit(0);
+ } else {
+ process.exit(0);
+ }
+ }
+
+ const imageTypes = ['jpeg', 'jpg', 'png', 'webp'];
+ const imagePatterns = imageTypes.map(type => `${publicDir}/**/*.${type}`);
+
+ let images = [];
+ imagePatterns.forEach(pattern => {
+ console.log(chalk.blue(`Searching with pattern: ${pattern}`));
+ const matches = glob.sync(pattern, { nocase: true });
+ console.log(chalk.yellow(` Found ${matches.length} matches`));
+ images = [...images, ...matches];
+ });
+
+ if (images.length === 0) {
+ console.log(chalk.yellow('No images found in the public directory.'));
+ process.exit(0);
+ }
+
+ console.log(chalk.green(`πŸ“· Found ${images.length} images to compress\n`));
+
+ const totalSize = { original: 0, compressed: 0 };
+ const failedImages = [];
+ const compressionResults = [];
+ const skippedImages = [];
+
+ let processedCount = 0;
+
+ console.log(chalk.blue('πŸ”„ Starting compression process...\n'));
+
+ if (detailedOutput) {
+ console.log(chalk.blue('File'.padEnd(60) + 'Original'.padEnd(15) + 'Compressed'.padEnd(15) + 'Savings'.padEnd(15) + 'Percent'));
+ console.log(chalk.blue('-'.repeat(105)));
+ }
+
+ for (const imagePath of images) {
+ const relativePath = path.relative(publicDir, imagePath);
+ const outputPath = path.join(compressedDir, relativePath);
+ const outputDir = path.dirname(outputPath);
+
+ processedCount++;
+
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
+ const stats = fs.statSync(imagePath);
+
+ const ext = path.extname(imagePath).toLowerCase();
+
+ try {
+ let sharpImage = sharp(imagePath);
+
+ if (ext === '.jpg' || ext === '.jpeg') {
+ sharpImage = sharpImage.jpeg({ quality: 85, mozjpeg: true });
+ } else if (ext === '.png') {
+ sharpImage = sharpImage.png({ compressionLevel: 8, adaptiveFiltering: true });
+ } else if (ext === '.webp') {
+ sharpImage = sharpImage.webp({ quality: 85 });
+ }
+
+ await sharpImage.toFile(outputPath);
+
+ const compressedStats = fs.statSync(outputPath);
+
+ const savings = stats.size - compressedStats.size;
+ const savingsPercent = (savings / stats.size * 100).toFixed(2);
+
+ if (compressedStats.size >= stats.size) {
+ skippedImages.push({
+ path: relativePath,
+ original: stats.size,
+ compressed: compressedStats.size,
+ difference: compressedStats.size - stats.size
+ });
+
+ fs.unlinkSync(outputPath);
+
+ if (detailedOutput) {
+ const displayPath = relativePath.length > 59 ? '...' + relativePath.slice(-56) : relativePath.padEnd(60);
+ console.log(
+ chalk.yellow(displayPath.padEnd(60) +
+ formatBytes(stats.size).padEnd(15) +
+ formatBytes(compressedStats.size).padEnd(15) +
+ `+${formatBytes(compressedStats.size - stats.size)}`.padEnd(15) +
+ `SKIPPED (would increase size)`)
+ );
+ }
+ } else {
+ totalSize.original += stats.size;
+ totalSize.compressed += compressedStats.size;
+
+ compressionResults.push({
+ path: relativePath,
+ original: stats.size,
+ compressed: compressedStats.size,
+ savings,
+ savingsPercent
+ });
+
+ if (detailedOutput) {
+ const displayPath = relativePath.length > 59 ? '...' + relativePath.slice(-56) : relativePath.padEnd(60);
+ console.log(
+ displayPath.padEnd(60) +
+ formatBytes(stats.size).padEnd(15) +
+ formatBytes(compressedStats.size).padEnd(15) +
+ formatBytes(savings).padEnd(15) +
+ `${savingsPercent}%`
+ );
+ }
+ }
+
+ if (!detailedOutput && (processedCount % 10 === 0 || processedCount === images.length)) {
+ process.stdout.write(`\r${chalk.blue('⏳ Progress:')} ${chalk.yellow(`${Math.floor((processedCount / images.length) * 100)}%`)} - Processed ${processedCount}/${images.length} images`);
+ }
+ } catch (error) {
+ failedImages.push({ path: relativePath, error: error.message });
+ if (detailedOutput) {
+ console.log(chalk.red(`${relativePath.padEnd(60)} ERROR: ${error.message}`));
+ }
+ }
+ }
+
+ if (!detailedOutput) {
+ process.stdout.write('\r' + ' '.repeat(100) + '\r');
+ }
+
+ const totalSavingsMB = ((totalSize.original - totalSize.compressed) / (1024 * 1024)).toFixed(2);
+ const totalSavingsPercent = totalSize.original > 0 ? ((totalSize.original - totalSize.compressed) / totalSize.original * 100).toFixed(2) : "0.00";
+
+ console.log('\n\n' + chalk.blue('πŸ“Š ===== Compression Summary ====='));
+ console.log(chalk.blue(`πŸ“¦ Original Size: ${chalk.yellow(formatBytes(totalSize.original))}`));
+ console.log(chalk.blue(`πŸ“¦ Compressed Size: ${chalk.yellow(formatBytes(totalSize.compressed))}`));
+ console.log(chalk.blue(`πŸ’° Saved: ${chalk.green(formatBytes(totalSize.original - totalSize.compressed))} (${chalk.green(totalSavingsPercent + '%')})`) + '\n');
+
+ if (skippedImages.length > 0) {
+ console.log(chalk.yellow(`⚠️ Skipped ${skippedImages.length} images that would become larger when compressed`));
+
+ skippedImages.sort((a, b) => b.difference - a.difference);
+
+ const worstOffenders = skippedImages.slice(0, Math.min(3, skippedImages.length));
+ console.log(chalk.yellow(' Top skipped images:'));
+ worstOffenders.forEach(img => {
+ console.log(chalk.yellow(` - ${img.path}: Would increase by ${formatBytes(img.difference)} (${formatBytes(img.original)} β†’ ${formatBytes(img.compressed)})`));
+ });
+ console.log();
+ }
+
+ if (compressionResults.length > 0) {
+ compressionResults.sort((a, b) => b.savingsPercent - a.savingsPercent);
+
+ const bestResult = compressionResults[0];
+ const worstResult = compressionResults[compressionResults.length - 1];
+
+ console.log(chalk.blue('πŸ† Best compression: ') +
+ chalk.green(`${bestResult.path} - ${bestResult.savingsPercent}% reduction (${formatBytes(bestResult.original)} β†’ ${formatBytes(bestResult.compressed)})`));
+
+ console.log(chalk.blue('⚠️ Least compression: ') +
+ chalk.yellow(`${worstResult.path} - ${worstResult.savingsPercent}% reduction (${formatBytes(worstResult.original)} β†’ ${formatBytes(worstResult.compressed)})`));
+
+ console.log();
+ }
+
+ if (failedImages.length > 0) {
+ console.log(chalk.red(`❌ Failed to compress ${failedImages.length} images:`));
+ failedImages.forEach(img => {
+ console.log(chalk.red(` - ${img.path}: ${img.error}`));
+ });
+ console.log('');
+ }
+
+ if (compressionResults.length === 0) {
+ console.log(chalk.yellow('No images were successfully compressed. No changes to apply.'));
+
+ fs.rmSync(compressedDir, { recursive: true, force: true });
+ process.exit(0);
+ }
+
+ console.log(chalk.blue(`πŸ” Compressed images are available in: ${chalk.yellow(compressedDir)}`));
+ console.log(chalk.blue(' You can compare the quality before applying changes.') + '\n');
+
+ let shouldApply = forceApply;
+
+ if (!forceApply) {
+ shouldApply = await askForConfirmation(chalk.yellow('Do you want to replace the original images with the compressed versions?'));
+ }
+
+ if (shouldApply) {
+ console.log(chalk.blue('\nπŸ”„ Replacing original images with compressed versions...'));
+
+ let replacedCount = 0;
+ for (const imagePath of images) {
+ const relativePath = path.relative(publicDir, imagePath);
+ const compressedPath = path.join(compressedDir, relativePath);
+
+ if (fs.existsSync(compressedPath)) {
+ fs.copyFileSync(compressedPath, imagePath);
+ replacedCount++;
+
+ const percentage = Math.floor((replacedCount / compressionResults.length) * 100);
+ process.stdout.write(`\r${chalk.blue('⏳ Progress:')} ${chalk.yellow(`${percentage}%`)} - Replacing image ${replacedCount}/${compressionResults.length}`);
+ }
+ }
+
+ process.stdout.write('\r' + ' '.repeat(100) + '\r');
+
+ fs.rmSync(compressedDir, { recursive: true, force: true });
+ console.log(chalk.green(`\nβœ… Success! ${replacedCount} images have been optimized and replaced.`));
+ if (skippedImages.length > 0) {
+ console.log(chalk.yellow(` Note: ${skippedImages.length} images were skipped because compression would have increased their size.`));
+ }
+ console.log(chalk.green(`🧹 Temporary compressed folder has been removed.`));
+ } else {
+ console.log(chalk.blue('\nπŸ‘€ No changes applied. You can:'));
+ console.log(chalk.blue(` 1. View the compressed images in ${chalk.yellow(compressedDir)}`));
+ console.log(chalk.blue(' 2. Run this tool again if you decide to apply changes'));
+ console.log(chalk.blue(' 3. Or manually replace images you want to use') + '\n');
+ }
+}
+
+main().catch(err => {
+ console.error('Error during image compression:', err);
+ process.exit(1);
+});
+EOL
+
+echo -e "${YELLOW}Installing dependencies (this may take a moment)...${NC}"
+npm install --no-fund --no-audit --silent
+
+if [ $? -ne 0 ]; then
+ echo -e "${RED}Failed to install dependencies.${NC}"
+ rm -rf "$TEMP_DIR"
+ exit 1
+fi
+
+echo -e "${GREEN}Dependencies installed. ${BLUE}Running image compression...${NC}\n"
+PROJECT_ROOT="$PROJECT_ROOT" node compress-images.js "$@"
+
+cd - > /dev/null
+rm -rf "$TEMP_DIR"
\ No newline at end of file