In modern web development, large image file sizes can slow page loads and increase upload times. Compressor.js is a lightweight front-end JavaScript library that compresses images in the browser using the native canvas.toBlob() API to reduce file size before uploading or processing. It supports popular formats like JPEG, PNG, and WebP, and allows fine-grained control over quality and dimensions.
Why Use Client-Side Compression
Before sending images to the server, compressing them on the client side can:
- Reduce upload bandwidth and server load
- Improve user experience with faster uploads
- Lower storage costs by limiting large image files
- Preserve user privacy since compression happens locally
Compressor.js is ideal for handling user-generated photos (e.g., avatars, galleries) directly in the browser.
Installing and Including Compressor.js
You can install or include Compressor.js in two main ways:
Via npm (modern projects):
npm install compressorjs
Then import in JavaScript:
import Compressor from 'compressorjs';
Via CDN (simple HTML):
<script src="https://cdn.jsdelivr.net/npm/compressorjs/dist/compressor.min.js"></script>
Basic Usage Example
Here’s a simple way to compress an image selected by a user before upload:
<input type="file" id="file" accept="image/*">
<script>
document.getElementById('file').addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
new Compressor(file, {
quality: 0.7,
success(result) {
// result is the compressed image Blob
uploadImage(result);
},
error(err) {
console.error(err.message);
},
});
});
function uploadImage(blob) {
const formData = new FormData();
formData.append('file', blob, blob.name);
// send formData via fetch or Axios
}
</script>
- quality: Compression quality (0.0–1.0). Lower = smaller file, reduced quality.
- success: Callback when compression completes.
- error: Error handling callback.
Useful Options and Configuration
Compressor.js supports several options to control compression behavior:
| Option | Description |
|---|---|
quality |
JPEG/WebP quality (0–1). |
maxWidth, maxHeight |
Maximum output dimensions. |
minWidth, minHeight |
Minimum dimensions to avoid tiny outputs. |
checkOrientation |
Auto-correct orientation based on EXIF data. |
retainExif |
Keep original EXIF metadata (if needed). |
mimeType |
Output format (e.g., image/webp). |
Example with size limits:
new Compressor(file, {
quality: 0.6,
maxWidth: 1024,
maxHeight: 1024,
mimeType: 'image/webp',
success(result) {
// ...
},
});
Best Practices and Tips
- Balance Quality vs Size: Lower
qualityreduces size but can affect visual fidelity. A common range is 0.5–0.8. - Prefer Dimensions Reduction: Reducing image dimensions (width/height) can yield bigger size savings with less perceived quality loss than aggressive quality reduction.
- Handle Orientation: Enable
checkOrientationfor mobile photos to ensure correct display. - Fallback Logic: If compression results in a larger file (possible at high quality), use original when necessary.
- Performance Considerations: Compressing many files at once can be slow; consider batching and showing user feedback.
Advanced Scenarios
- Automatic Target Size Compression: Some implementations use repeated compression with decreasing quality until the final size is below a target threshold (e.g., 500 KB). This recursive pattern can improve control over final file size.
- Integration with Upload Plugins: Libraries like Uppy use Compressor.js internally to optimize images before upload and can be configured with quality and concurrency settings.
Conclusion
Compressor.js is an efficient and easy-to-use front-end image compression library that helps you optimize images directly in the browser before upload. It supports key options like quality, resizing, and orientation correction, and can boost performance for web apps with image upload features. By combining sensible defaults and best practices, you can significantly reduce file sizes while maintaining good visual quality.