comprez
Version:
Modern image compression library for Node.js, Browser, and serverless environments
232 lines (165 loc) • 6.16 kB
Markdown
# Comprez
TypeScript-native, universal image compression for Node.js, browsers, and serverless environments with optimized engines per platform.
## Features
- **Universal Support**: Node.js, browsers, and serverless environments
- **Format Support**: JPEG, PNG, WebP, and AVIF compression
- **Smart Engine Selection**: Sharp in Node.js, Canvas API in browsers
- **TypeScript Native**: Fully typed with comprehensive definitions
- **Resize Capabilities**: Aspect ratio preservation with configurable dimensions
## Installation
```bash
npm install comprez
```
### Peer Dependencies
For Node.js environments, Sharp is recommended for optimal performance:
```bash
npm install sharp
```
Sharp is optional and will be automatically detected if available.
## Demo
Try Comprez in action: **[Live Demo](https://comprez-demo.vercel.app/)**
## Quick Start
```typescript
import { compressImage } from 'comprez';
// Node.js
const buffer = fs.readFileSync('input.jpg');
const result = await compressImage(buffer, {
quality: 0.8,
format: 'webp',
maxWidth: 1200
});
// Browser
const handleFileUpload = async (file: File) => {
const result = await compressImage(file, {
quality: 0.8,
format: 'webp',
maxWidth: 800
});
const blob = new Blob([result.buffer], { type: result.mimeType });
return URL.createObjectURL(blob);
};
```
## Advanced Features
### Batch Processing
```typescript
import { compressImages } from 'comprez';
const images = ['image1.jpg', 'image2.png', 'image3.webp'];
const results = await compressImages(images, {
quality: 0.8,
format: 'webp',
maxWidth: 1200
});
```
### Streaming Support (Node.js)
```typescript
import { compressImageStream } from 'comprez/node';
import fs from 'fs';
const inputStream = fs.createReadStream('large-image.jpg');
const result = await compressImageStream(inputStream, {
quality: 0.8,
format: 'avif',
onProgress: (progress) => console.log(`Progress: ${progress}%`)
});
```
### Environment Detection
```typescript
import { getCurrentEngineType, getEngineCapabilities } from 'comprez';
const engine = getCurrentEngineType(); // 'node' | 'browser' | 'unknown'
const capabilities = await getEngineCapabilities();
console.log('Supported formats:', capabilities.formats);
```
## API Reference
### `compressImage(input, options?)`
Compress a single image with the specified options.
#### Parameters
- **input**: `Buffer | File | string`
- `Buffer`: Image buffer (Node.js)
- `File`: File object (Browser)
- `string`: URL or data URL
- **options**: `CompressionOptions` (optional)
```typescript
{
maxWidth?: number; // Maximum width in pixels
maxHeight?: number; // Maximum height in pixels
quality?: number; // Quality (0-1, default: 0.8)
format?: 'auto' | 'jpeg' | 'png' | 'webp' | 'avif';
enableLogging?: boolean; // Enable compression logging
}
```
#### Returns
```typescript
{
buffer: Buffer; // Compressed image buffer
sizeBefore: number; // Original size in bytes
sizeAfter: number; // Compressed size in bytes
mimeType: string; // Output MIME type
compressionRatio: number; // Size ratio (sizeAfter / sizeBefore)
}
```
### `compressImages(inputs, options?)`
Compress multiple images in parallel.
```typescript
const results = await compressImages([buffer1, buffer2], {
quality: 0.8,
format: 'webp'
});
```
### `getOptimalFormat(input)`
Get the recommended format for an image based on browser capabilities.
```typescript
const format = await getOptimalFormat(imageBuffer);
// Returns: 'avif' | 'webp' | 'jpeg' | 'png'
```
## How It Works
Comprez uses a dual-engine architecture that automatically selects the optimal compression method:
- **Node.js**: Uses Sharp (libvips) for high-performance compression
- **Browser**: Uses Canvas API for universal compatibility
- **Serverless**: Automatically adapts to available resources
Environment detection happens at runtime, seamlessly switching between engines without requiring different APIs or configurations.
## API Reference
### `compressImage(input, options?)`
Compress a single image with the specified options.
**Parameters:**
- `input`: `Buffer | File | string` - Image input (Buffer in Node.js, File in browser, URL string)
- `options`: `CompressionOptions` - Compression configuration
**Returns:** `Promise<CompressionResult>`
```typescript
interface CompressionOptions {
quality?: number; // 0-1, default: 0.8
format?: ImageFormat; // 'auto' | 'jpeg' | 'png' | 'webp' | 'avif'
maxWidth?: number; // Maximum width
maxHeight?: number; // Maximum height
enableLogging?: boolean; // Enable compression logging
}
interface CompressionResult {
buffer: Buffer | Uint8Array;
sizeBefore: number;
sizeAfter: number;
mimeType: string;
compressionRatio: number;
}
```
### `compressImages(inputs, options?)`
Compress multiple images with the same options.
### `getCurrentEngineType()`
Returns the current engine type: `'node' | 'browser' | 'unknown'`
### `getEngineCapabilities()`
Returns the capabilities of the current engine including supported formats and features.
## Format Support
| Format | Input | Output | Node.js | Browser | Quality Control |
|--------|-------|--------|---------|---------|-----------------|
| JPEG | ✅ | ✅ | ✅ | ✅ | ✅ |
| PNG | ✅ | ✅ | ✅ | ✅ | ❌ (lossless) |
| WebP | ✅ | ✅ | ✅ | ✅* | ✅ |
| AVIF | ✅ | ✅ | ✅ | ✅* | ✅ |
*Browser support depends on browser capabilities
## Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests for any improvements.
## License
MIT © [Your Name]
## Links
- [Live Demo](https://comprez-demo.vercel.app/) - Interactive compression demo
- [GitHub Repository](https://github.com/ignaciojsoler/comprez)
- [NPM Package](https://www.npmjs.com/package/comprez)
- [Documentation](https://github.com/ignaciojsoler/comprez#readme)
- [Issues](https://github.com/ignaciojsoler/comprez/issues)