-
-
Notifications
You must be signed in to change notification settings - Fork 152
feat: add automated image optimization pipeline with Sharp #243
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Rozerxshashank
wants to merge
5
commits into
AOSSIE-Org:dev
Choose a base branch
from
Rozerxshashank:optimize-img-feat
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+251
−6
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
dfd7e6b
feat: add automated image optimization pipeline with Sharp
Rozerxshashank e63e8a3
fix: only replace images if compression reduces size
Rozerxshashank d214744
chore: add package-lock.json with Sharp dependency
Rozerxshashank 8908aaa
feat: make image discovery dynamic - auto-find all PNG files
Rozerxshashank e7dc649
feat: extend image optimization to support PNG, JPG, and WebP formats
Rozerxshashank File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| /** | ||
| * Image Optimization Script | ||
| * | ||
| * Uses Sharp to compress PNG images and generate WebP versions. | ||
| * Run with: npm run optimize-images | ||
| */ | ||
|
|
||
| const sharp = require('sharp'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
|
|
||
| const ASSETS_DIR = path.join(__dirname, '..', 'app', 'assets'); | ||
| const PNG_QUALITY = 80; | ||
| const WEBP_QUALITY = 80; | ||
|
|
||
| // Images to optimize (large PNG files) | ||
| const IMAGES_TO_OPTIMIZE = [ | ||
| 'resonate_app.png', | ||
| 'Vector.png', | ||
| 'Group.png', | ||
| 'createrooms.png', | ||
| 'roomscreen.png', | ||
| 'pairchat.png', | ||
| 'chatscreen.png', | ||
| 'aossie_logo.png', | ||
| 'PlayStore.png', | ||
| ]; | ||
|
Rozerxshashank marked this conversation as resolved.
Outdated
|
||
|
|
||
| async function getFileSize(filePath) { | ||
| try { | ||
| const stats = await fs.promises.stat(filePath); | ||
| return stats.size; | ||
| } catch (error) { | ||
| // File doesn't exist or is inaccessible | ||
| return 0; | ||
| } | ||
| } | ||
|
|
||
| async function fileExists(filePath) { | ||
| try { | ||
| await fs.promises.access(filePath, fs.constants.F_OK); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| function formatBytes(bytes) { | ||
| if (bytes === 0) return '0 Bytes'; | ||
| const k = 1024; | ||
| const sizes = ['Bytes', 'KB', 'MB']; | ||
| const i = Math.floor(Math.log(bytes) / Math.log(k)); | ||
| return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; | ||
| } | ||
|
|
||
| async function optimizeImage(filename) { | ||
| const inputPath = path.join(ASSETS_DIR, filename); | ||
| const tempPath = path.join(ASSETS_DIR, `temp_${filename}`); | ||
| const webpPath = path.join(ASSETS_DIR, filename.replace('.png', '.webp')); | ||
|
|
||
| // Check if file exists | ||
| if (!await fileExists(inputPath)) { | ||
| console.log(`Skipping ${filename} - file not found`); | ||
| return null; | ||
| } | ||
|
|
||
| const originalSize = await getFileSize(inputPath); | ||
|
|
||
| try { | ||
| // Compress PNG | ||
| await sharp(inputPath) | ||
| .png({ | ||
| quality: PNG_QUALITY, | ||
| compressionLevel: 9 | ||
| }) | ||
| .toFile(tempPath); | ||
|
|
||
| // Atomically replace original with compressed version | ||
| // rename() overwrites the destination if it exists (atomic on same filesystem) | ||
| await fs.promises.rename(tempPath, inputPath); | ||
|
|
||
| const compressedSize = await getFileSize(inputPath); | ||
|
|
||
| // Generate WebP version | ||
| await sharp(inputPath) | ||
| .webp({ quality: WEBP_QUALITY }) | ||
| .toFile(webpPath); | ||
|
|
||
| const webpSize = await getFileSize(webpPath); | ||
|
|
||
| return { | ||
| filename, | ||
| originalSize, | ||
| compressedSize, | ||
| webpSize, | ||
| savings: originalSize - compressedSize, | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| savingsPercent: originalSize > 0 | ||
| ? ((originalSize - compressedSize) / originalSize * 100).toFixed(1) | ||
| : '0.0' | ||
| }; | ||
| } catch (error) { | ||
| console.error(`Error optimizing ${filename}:`, error.message); | ||
| // Clean up temp file if it exists | ||
| if (await fileExists(tempPath)) { | ||
| await fs.promises.unlink(tempPath); | ||
| } | ||
|
Comment on lines
+149
to
+154
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Guard cleanup unlink inside catch to preserve per-file fault isolation. At Line 153, if 🧯 Suggested hardening } catch (error) {
console.error(`Error optimizing ${filename}:`, error.message);
// Clean up temp file if it exists
if (await fileExists(tempPath)) {
- await fs.promises.unlink(tempPath);
+ try {
+ await fs.promises.unlink(tempPath);
+ } catch (cleanupError) {
+ console.error(`Failed to clean temp file for ${filename}:`, cleanupError.message);
+ }
}
return null;
}🤖 Prompt for AI Agents |
||
| return null; | ||
| } | ||
| } | ||
|
|
||
| async function main() { | ||
| console.log('\nImage Optimization Script\n'); | ||
| console.log('='.repeat(60)); | ||
|
|
||
| const results = []; | ||
| let totalOriginal = 0; | ||
| let totalCompressed = 0; | ||
|
|
||
| for (const filename of IMAGES_TO_OPTIMIZE) { | ||
| process.stdout.write(`Processing ${filename}... `); | ||
| const result = await optimizeImage(filename); | ||
|
|
||
| if (result) { | ||
| results.push(result); | ||
| totalOriginal += result.originalSize; | ||
| totalCompressed += result.compressedSize; | ||
| console.log(`Done - Saved ${result.savingsPercent}%`); | ||
| } | ||
| } | ||
|
|
||
| console.log('\n' + '='.repeat(60)); | ||
| console.log('\nOptimization Results:\n'); | ||
| console.log('| Image | Original | Compressed | WebP | Savings |'); | ||
| console.log('|-------|----------|------------|------|---------|'); | ||
|
|
||
| for (const r of results) { | ||
| console.log(`| ${r.filename.substring(0, 20).padEnd(20)} | ${formatBytes(r.originalSize).padEnd(8)} | ${formatBytes(r.compressedSize).padEnd(10)} | ${formatBytes(r.webpSize).padEnd(6)} | ${r.savingsPercent}% |`); | ||
| } | ||
|
|
||
| console.log('\n' + '='.repeat(60)); | ||
|
|
||
| // Prevent division by zero if no images were processed | ||
| if (totalOriginal === 0) { | ||
| console.log('\nNo images were processed.\n'); | ||
| return; | ||
| } | ||
|
|
||
| console.log(`\nTotal: ${formatBytes(totalOriginal)} -> ${formatBytes(totalCompressed)}`); | ||
| console.log(`Saved: ${formatBytes(totalOriginal - totalCompressed)} (${((totalOriginal - totalCompressed) / totalOriginal * 100).toFixed(1)}%)\n`); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| main().catch(console.error); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.