@toolcore/image-compress
v1.0.2
Published
An image compression tool
Readme
Image Compress
A lightweight, efficient image compression library for modern web applications. Supports multiple image formats, directional transformations, and quality-based compression.
Installation
npm install image-compress
# or
yarn add image-compressFeatures
- 🖼️ Multiple image format support (JPEG, PNG, GIF, JPG)
- 🔄 Direction and orientation transformations
- ⚡ Efficient compression algorithms
- 📱 Responsive image resizing
- 🎯 Precise file size control
- 🔧 TypeScript support
- 🚀 Promise-based API
Quick Start
import { Compress, EImageType } from 'image-compress';
// Create compressor instance
const compressor = new Compress({
size: 1024, // Target size in KB
quality: 0.8,
type: EImageType.JPEG,
width: 800,
height: 600
});
// Compress image file
const inputFile = document.getElementById('file-input').files[0];
const compressedFile = await compressor.compress(inputFile);
// Use compressed file
const formData = new FormData();
formData.append('image', compressedFile);
await fetch('/upload', { method: 'POST', body: formData });API Documentation
Compress Class
The main class for image compression operations.
Constructor
new Compress(config?: Partial<ICompressOptions>)Parameters:
config(Optional): Compression configuration options
Example:
const compressor = new Compress({
size: 500,
quality: 0.7,
type: EImageType.PNG
});Methods
compress(file: File): Promise
Compresses an image file while maintaining visual quality.
Parameters:
file: The image file to compress
Returns: Promise that resolves to compressed File object
Example:
const compressedFile = await compressor.compress(originalFile);Configuration Options
ICompressOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| size | number | 1024 | Target file size in kilobytes (KB) |
| type | EImageType | EImageType.JPEG | Output image format |
| width | number | 375 | Output image width in pixels |
| height | number | 375 | Output image height in pixels |
| quality | number | 0.8 | Compression quality (0-1) |
| direction | IDirection | 1 | Image orientation/direction |
| scale | number | 1 | Scale factor (0.1-10) |
Image Types
EImageType
Supported image formats:
enum EImageType {
PNG = 'image/png',
JPEG = 'image/jpeg',
GIF = 'image/gif',
JPG = 'image/jpg'
}Direction Transformations
IDirection
Image orientation and transformation options:
| Value | Description |
|-------|-------------|
| 1 | 0° (Normal) |
| 2 | Horizontal flip |
| 3 | 180° rotation |
| 4 | Vertical flip |
| 5 | 90° clockwise + horizontal flip |
| 6 | 90° clockwise |
| 7 | 90° clockwise + vertical flip |
| 8 | 90° counter-clockwise |
Advanced Usage
Custom Compression Settings
const advancedCompressor = new Compress({
size: 2048, // 2MB target
quality: 0.9, // High quality
type: EImageType.PNG, // PNG format
width: 1920, // HD width
height: 1080, // HD height
direction: 6, // Rotate 90° clockwise
scale: 0.5 // Scale down to 50%
});
const result = await advancedCompressor.compress(largeImageFile);Error Handling
try {
const compressedFile = await compressor.compress(inputFile);
// Handle success
} catch (error) {
console.error('Compression failed:', error.message);
// Handle specific error types
if (error.message.includes('file type')) {
// Unsupported file type
} else if (error.message.includes('quality')) {
// Invalid quality parameter
}
}Browser Support
- Chrome 50+
- Firefox 55+
- Safari 11+
- Edge 79+
Performance Notes
- Uses HTML5 Canvas for image processing
- Implements binary search for optimal compression quality
- Base64 encoding overhead is accounted for in size calculations
- Memory efficient with proper cleanup
File Size Calculation
The library uses a sophisticated algorithm to achieve target file sizes:
- Target Range:
[size × quality, size × (2 - quality)]KB - Optimal Target:
sizeKB - Base64 Adjustment: Automatically accounts for Base64 encoding overhead
Common Use Cases
Mobile Image Upload
const mobileCompressor = new Compress({
size: 500, // 500KB for mobile networks
width: 1080, // Optimized for mobile displays
quality: 0.8 // Good quality with small size
});Social Media Images
const socialCompressor = new Compress({
size: 1024, // Common social media limit
type: EImageType.JPEG, // Preferred format
quality: 0.85 // Balance quality and size
});E-commerce Product Images
const productCompressor = new Compress({
size: 2048, // Higher quality for products
type: EImageType.JPEG,
quality: 0.9, // Maximum quality
scale: 1 // Maintain original dimensions
});Troubleshooting
Common Issues
- Large output files: Reduce
qualityorsizeparameters - Poor image quality: Increase
qualityparameter - Unsupported format: Ensure input is JPEG, PNG, or GIF
- Memory issues: Process smaller batches or reduce dimensions
Debug Mode
For development debugging, monitor the compression process:
// Add logging to understand compression steps
const originalSize = file.size;
const compressedFile = await compressor.compress(file);
const compressionRatio = (originalSize / compressedFile.size).toFixed(2);
console.log(`Compressed from ${originalSize} to ${compressedFile.size} bytes (${compressionRatio}x)`);License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.
Changelog
v1.0.0
- Initial release
- Core compression functionality
- Multiple format support
- Direction transformations
