@lavvordev/image-shrink
v1.1.1
Published
High-performance Node.js image optimizer: WebP, AVIF, responsive multiples, CLI. 70-90% smaller.
Downloads
255
Maintainers
Readme
@lavvordev/image-shrink
High-performance Node.js image optimizer that reduces image size by 70-90% with zero configuration. Converts to WebP, strips metadata, generates responsive multiples, and includes a CLI.
Why this package?
Most image optimization tools either:
- Write temp files to disk (slow, messy)
- Crash your server on corrupted uploads (amateur)
- Require 50 lines of configuration (frustrating)
This package does none of that. In-memory, fail-safe, zero-config.
Features
- 70-90% size reduction � WebP conversion with quality tuning
- In-memory processing � no temp files, no disk I/O overhead
- Metadata stripping � removes EXIF, GPS, timestamps (nobody needs your photo's geolocation)
- Responsive multiples � generate 400w, 800w, 1200w sizes in one call
- CLI tool � compress images without writing code
- Express middleware � drop into existing upload endpoints
- Fail-safe � corrupted images don't crash your server
- TypeScript � full type definitions included
Installation
npm install @lavvordev/image-shrink
Quick Start (Node.js API)
javascript
import { shrinkImage } from '@lavvordev/image-shrink';
import fs from 'fs';
const input = fs.readFileSync('huge-photo.jpg');
const result = await shrinkImage(input, {
format: 'webp',
quality: 75,
maxWidth: 1200
});
console.log(`Saved ${result.savedPercent}%`);
fs.writeFileSync('optimized.webp', result.buffer);
CLI Usage (No Code Required)
Install globally:
bash
npm install -g @lavvordev/image-shrink
Then run from anywhere:
bash
image-shrink photo.jpg -o compressed.webp -q 75 -w 1200
Or use npx without installing:
bash
npx @lavvordev/image-shrink photo.jpg
CLI Options
Option Description
-o, --output Output file path
-q, --quality Quality 1-100 (default: 80)
-f, --format webp, jpeg, png, avif (default: webp)
-w, --max-width Maximum width (preserves aspect ratio)
-h, --max-height Maximum height (preserves aspect ratio)
--keep-metadata Don't strip EXIF/GPS data
--fail-on-error Throw instead of silent fallback
Responsive Images (Generate Multiple Sizes)
Perfect for HTML srcset:
import { generateResponsiveSizes } from '@lavvordev/image-shrink';
const sizes = await generateResponsiveSizes(inputBuffer, {
widths: [400, 800, 1200, 1600],
format: 'webp',
quality: 75
});
// sizes.forEach(size => {
// fs.writeFileSync(`photo-${size.width}.webp`, size.buffer);
// });
This generates four WebP files at different resolutions from a single input. Each maintains aspect ratio and is optimized individually.
Express Middleware
import express from 'express';
import multer from 'multer';
import { imageShrinkMiddleware } from '@lavvordev/image-shrink/express';
const app = express();
const upload = multer({ storage: multer.memoryStorage() });
app.post('/upload', upload.single('image'), imageShrinkMiddleware({
quality: 80,
maxWidth: 800
}), (req, res) => {
// req.optimizedBuffer � ready to save
// req.shrinkStats.originalSize / shrunkSize / savedPercent
res.json({ saved: req.shrinkStats.savedPercent });
});
API Reference
shrinkImage(input, options)
Parameter Type Description
input Buffer | Uint8Array | string Image data or base64
options ImageShrinkOptions Optional config
Returns: Promise<ShrinkResult>
ImageShrinkOptions
Property Type Default Description
format 'webp'|'jpeg'|'png'|'avif' 'webp' Output format
quality number 80 1-100
stripMetadata boolean true Remove EXIF/GPS
maxWidth number undefined Max width
maxHeight number undefined Max height
failOnError boolean false Throw instead of fallback
ShrinkResult
Property Type Description
buffer Buffer Optimized image
originalSize number Input bytes
shrunkSize number Output bytes
outputFormat string Format used
savedPercent number Reduction percentage
Performance Benchmarks
Tested on 6.2 MB smartphone photo (4032x3024 JPEG):
Operation Result Size Time Reduction
WebP (quality 80) 187 KB 342 ms 97.0%
WebP (quality 70) 121 KB 328 ms 98.1%
JPEG (quality 80) 421 KB 291 ms 93.2%
Responsive (4 sizes) 560 KB total 890 ms 91.0%
Use Cases
User avatars � enforce max dimensions on profile uploads
E-commerce galleries � batch optimize before S3 upload
CMS image pipelines � automatic WebP conversion
SaaS file handlers � reduce cloud storage costs
Static site generators � pre-optimize blog images
Comparison with sharp
Feature sharp @lavvordev/image-shrink
Zero config No Yes
Responsive multiples Manual loop One function call
CLI tool No Yes
Express middleware Manual wrapper Included
Fail-safe fallback No Yes (default)
Base64 input Manual conversion Automatic
This package is a wrapper around sharp that adds ergonomics, not a replacement. Use sharp for advanced manipulation; use this for 80% of common optimization tasks.
Error Handling
By default, shrinkImage never throws. Corrupted or invalid inputs return the original buffer with outputFormat: 'original'. Set failOnError: true to throw exceptions.
I've seen this break before when users assume a corrupted image will throw. It won't. That's intentional.
Browser Compatibility
WebP, JPEG, PNG, AVIF are supported in all modern browsers. For legacy browsers, implement client-side format detection or serve JPEG fallbacks.
Contributing
See CONTRIBUTING.md.
License
MIT � lavvordev