feat(core): add progressive JPEG support and fix Sharp format switching
This commit is contained in:
369
readme.md
369
readme.md
@@ -1,89 +1,356 @@
|
||||
# @push.rocks/smartjimp
|
||||
a tool fr working with images in TypeScript
|
||||
# @push.rocks/smartjimp 🖼️
|
||||
|
||||
## Install
|
||||
**Lightning-fast image processing for TypeScript, powered by Sharp and Jimp**
|
||||
|
||||
To install `@push.rocks/smartjimp`, use the following command in your project directory:
|
||||
[](https://www.npmjs.com/package/@push.rocks/smartjimp)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](./license)
|
||||
|
||||
## Why SmartJimp? 🚀
|
||||
|
||||
SmartJimp bridges the gap between two powerful image processing libraries:
|
||||
- **Sharp** 🗡️ - Blazing fast, native C++ bindings, perfect for production
|
||||
- **Jimp** 🎨 - Pure JavaScript, runs anywhere Node.js does
|
||||
|
||||
Choose your engine based on your needs - same API, different performance characteristics. Plus, you get automatic caching out of the box!
|
||||
|
||||
## Installation 📦
|
||||
|
||||
```bash
|
||||
# Using npm
|
||||
npm install @push.rocks/smartjimp --save
|
||||
|
||||
# Using pnpm (recommended)
|
||||
pnpm add @push.rocks/smartjimp
|
||||
|
||||
# Using yarn
|
||||
yarn add @push.rocks/smartjimp
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`@push.rocks/smartjimp` is a comprehensive TypeScript library for handling image processing with ease and efficiency. It leverages powerful image processing libraries such as `sharp` and `jimp`, providing a unified interface for performing common image manipulation tasks. This documentation aims to guide you through the installation and various functionalities of `@push.rocks/smartjimp`, ensuring you have the knowledge to integrate image processing capabilities into your TypeScript project effectively.
|
||||
|
||||
### Getting Started
|
||||
|
||||
First, import the `SmartJimp` class from the package:
|
||||
## Quick Start 🏃♂️
|
||||
|
||||
```typescript
|
||||
import { SmartJimp } from '@push.rocks/smartjimp';
|
||||
|
||||
// Choose your engine
|
||||
const imageProcessor = new SmartJimp({ mode: 'sharp' }); // or 'jimp'
|
||||
|
||||
// That's it! You're ready to process images 🎉
|
||||
```
|
||||
|
||||
Next, create an instance of `SmartJimp` by specifying the preferred image processing mode (`sharp` or `jimp`):
|
||||
|
||||
```typescript
|
||||
const imageProcessor = new SmartJimp({ mode: 'sharp' });
|
||||
```
|
||||
|
||||
### Processing Images
|
||||
|
||||
#### From Buffer
|
||||
|
||||
You can process images from a buffer. This is particularly useful when you have image data already available in your application, such as uploaded images.
|
||||
## Features ✨
|
||||
|
||||
### 🔄 Resize Images
|
||||
Resize images while maintaining aspect ratio or set exact dimensions:
|
||||
|
||||
```typescript
|
||||
import { SmartJimp } from '@push.rocks/smartjimp';
|
||||
import { SmartFile } from '@push.rocks/smartfile';
|
||||
|
||||
// Assuming you have an image buffer `imageBuffer`
|
||||
let imageBuffer: Buffer;
|
||||
const processor = new SmartJimp({ mode: 'sharp' });
|
||||
|
||||
// Convert the buffer to a SmartFile instance
|
||||
const smartfileInstance = await SmartFile.fromBuffer(imageBuffer);
|
||||
// Load an image
|
||||
const imageFile = await SmartFile.fromUrl('https://example.com/image.jpg');
|
||||
|
||||
// Process the image, for example, resizing it to width 500px
|
||||
const resizedImageBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
|
||||
width: 500,
|
||||
// Resize to 500px width (height auto-calculated to maintain aspect ratio)
|
||||
const resized = await processor.getFromSmartfile(imageFile, {
|
||||
width: 500
|
||||
});
|
||||
|
||||
// Or resize to exact dimensions
|
||||
const exactSize = await processor.getFromSmartfile(imageFile, {
|
||||
width: 800,
|
||||
height: 600
|
||||
});
|
||||
|
||||
// Save the result
|
||||
await SmartFile.fromBuffer('./resized.jpg', resized).write();
|
||||
```
|
||||
|
||||
#### Creating Specific Formats
|
||||
|
||||
`@push.rocks/smartjimp` supports creating images in various formats, including AVIF, WebP, and PNG.
|
||||
### 🎨 Format Conversion
|
||||
Convert between PNG, JPEG, WebP, and AVIF formats with ease:
|
||||
|
||||
```typescript
|
||||
// For forcing a format, specify the `format` in the options, like 'png'
|
||||
const pngBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
|
||||
width: 500,
|
||||
format: 'png',
|
||||
// Convert any image to PNG
|
||||
const pngBuffer = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'png'
|
||||
});
|
||||
|
||||
// Convert to standard JPEG
|
||||
const jpegBuffer = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'jpeg'
|
||||
});
|
||||
|
||||
// Convert to WebP for smaller file sizes
|
||||
const webpBuffer = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'webp',
|
||||
width: 1200 // Resize while converting!
|
||||
});
|
||||
|
||||
// Convert to AVIF for next-gen compression (Sharp only)
|
||||
const avifBuffer = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'avif'
|
||||
});
|
||||
```
|
||||
|
||||
### Advanced Image Manipulation
|
||||
|
||||
#### Inversion
|
||||
|
||||
You can invert the colors of an image as follows:
|
||||
### 📸 Progressive JPEG Support
|
||||
Create progressive JPEGs that load in multiple passes for better perceived performance:
|
||||
|
||||
```typescript
|
||||
const invertedImageBuffer = await imageProcessor.getFromSmartfile(smartfileInstance, {
|
||||
invert: true,
|
||||
// Create a progressive JPEG (Sharp mode only)
|
||||
const progressiveJpeg = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'jpeg',
|
||||
progressive: true,
|
||||
width: 800
|
||||
});
|
||||
|
||||
// Convert PNG to progressive JPEG
|
||||
const pngFile = await SmartFile.fromUrl('https://example.com/image.png');
|
||||
const progressiveFromPng = await processor.getFromSmartfile(pngFile, {
|
||||
format: 'jpeg',
|
||||
progressive: true
|
||||
});
|
||||
|
||||
// Standard JPEG (non-progressive)
|
||||
const standardJpeg = await processor.getFromSmartfile(imageFile, {
|
||||
format: 'jpeg',
|
||||
progressive: false // default
|
||||
});
|
||||
```
|
||||
|
||||
### Performance and Caching
|
||||
> 💡 **Note**: Progressive JPEG encoding is only supported in Sharp mode. Jimp will create standard JPEGs regardless of the progressive setting.
|
||||
|
||||
`@push.rocks/smartjimp` employs caching mechanisms to enhance performance. Caching is handled internally, ensuring that repeated processing requests for the same image and settings are served faster by retrieving the processed image from the cache.
|
||||
### 🔄 Image Effects
|
||||
Apply visual effects to your images:
|
||||
|
||||
### Mode: Sharp vs. Jimp
|
||||
```typescript
|
||||
// Invert colors (currently jimp-only)
|
||||
const inverted = await processor.getFromSmartfile(imageFile, {
|
||||
invert: true
|
||||
});
|
||||
```
|
||||
|
||||
- **Sharp**: Recommended for performance-critical applications. It is faster and supports a broader range of image formats. However, it relies on native libraries, which may need additional setup in certain environments.
|
||||
- **Jimp**: A pure JavaScript image processing library. While not as fast as Sharp, it guarantees compatibility across all Node.js environments without the need for additional native dependencies.
|
||||
### ⚡ Direct Buffer Processing
|
||||
Work directly with buffers for maximum flexibility:
|
||||
|
||||
### Conclusion
|
||||
```typescript
|
||||
// Process raw image buffers
|
||||
const processedBuffer = await processor.computeAssetVariation(imageBuffer, {
|
||||
width: 300,
|
||||
format: 'webp',
|
||||
invert: true
|
||||
});
|
||||
|
||||
`@push.rocks/smartjimp` makes image processing in TypeScript applications highly accessible and efficient. Whether you need to resize, convert formats, or perform other image manipulations, `@push.rocks/smartjimp` provides a powerful yet simple API to accomplish these tasks with minimal effort. By abstracting away the complexities of direct interactions with libraries like `sharp` and `jimp`, it allows developers to focus more on building the core features of their applications.
|
||||
// Create progressive JPEG from buffer
|
||||
const progressiveBuffer = await processor.computeAssetVariation(imageBuffer, {
|
||||
format: 'jpeg',
|
||||
progressive: true
|
||||
});
|
||||
|
||||
// Special AVIF creation method (sharp mode only)
|
||||
const avifBuffer = await processor.createAvifImageFromBuffer(imageBuffer);
|
||||
```
|
||||
|
||||
### 🚀 Built-in Caching
|
||||
SmartJimp automatically caches processed images for lightning-fast repeated operations:
|
||||
|
||||
```typescript
|
||||
// First call: processes the image
|
||||
const result1 = await processor.getFromSmartfile(imageFile, { width: 500 });
|
||||
|
||||
// Second call: returns from cache instantly! ⚡
|
||||
const result2 = await processor.getFromSmartfile(imageFile, { width: 500 });
|
||||
```
|
||||
|
||||
Cache features:
|
||||
- Automatic cache key generation based on source and parameters
|
||||
- 10-minute default TTL
|
||||
- Memory + disk hybrid caching with LevelCache
|
||||
|
||||
## Sharp vs Jimp: Choose Your Fighter 🥊
|
||||
|
||||
### Use Sharp when:
|
||||
- 🏃♂️ **Performance is critical** - Up to 10x faster than Jimp
|
||||
- 🎯 **You need AVIF support** - Sharp exclusive feature
|
||||
- 📸 **You need progressive JPEGs** - Sharp exclusive feature
|
||||
- 🖥️ **Running on servers** - Where native dependencies are OK
|
||||
- 📦 **Processing many images** - Batch operations benefit from speed
|
||||
|
||||
### Use Jimp when:
|
||||
- 🌍 **Cross-platform compatibility is key** - Pure JavaScript, no build steps
|
||||
- ☁️ **Deploying to serverless** - Some platforms don't support native modules
|
||||
- 🎨 **You need pixel-level manipulation** - Jimp has more pixel manipulation features
|
||||
- 🛠️ **Simpler deployment** - No need to worry about sharp's native dependencies
|
||||
|
||||
## Advanced Examples 🎓
|
||||
|
||||
### Batch Processing with Async Operations
|
||||
```typescript
|
||||
import { SmartJimp } from '@push.rocks/smartjimp';
|
||||
import { SmartFile } from '@push.rocks/smartfile';
|
||||
|
||||
const processor = new SmartJimp({ mode: 'sharp' });
|
||||
|
||||
// Process multiple images concurrently
|
||||
const imageUrls = [
|
||||
'https://example.com/photo1.jpg',
|
||||
'https://example.com/photo2.jpg',
|
||||
'https://example.com/photo3.jpg'
|
||||
];
|
||||
|
||||
const processedImages = await Promise.all(
|
||||
imageUrls.map(async (url) => {
|
||||
const file = await SmartFile.fromUrl(url);
|
||||
return processor.getFromSmartfile(file, {
|
||||
width: 800,
|
||||
format: 'jpeg',
|
||||
progressive: true // Web-optimized progressive JPEGs
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// Save all processed images
|
||||
await Promise.all(
|
||||
processedImages.map((buffer, index) =>
|
||||
SmartFile.fromBuffer(`./output/image-${index}.jpg`, buffer).write()
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
### Creating Responsive Image Sets
|
||||
```typescript
|
||||
// Generate multiple sizes for responsive images
|
||||
const sizes = [320, 640, 1024, 1920];
|
||||
const formats = ['webp', 'jpeg'] as const;
|
||||
|
||||
for (const size of sizes) {
|
||||
for (const format of formats) {
|
||||
const processed = await processor.getFromSmartfile(originalImage, {
|
||||
width: size,
|
||||
format,
|
||||
// Use progressive for JPEGs
|
||||
progressive: format === 'jpeg'
|
||||
});
|
||||
|
||||
await SmartFile.fromBuffer(
|
||||
`./responsive/image-${size}.${format}`,
|
||||
processed
|
||||
).write();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Web-Optimized Image Pipeline
|
||||
```typescript
|
||||
// Create a complete image optimization pipeline
|
||||
async function optimizeForWeb(sourceImage: SmartFile) {
|
||||
const processor = new SmartJimp({ mode: 'sharp' });
|
||||
|
||||
// Create multiple formats for browser compatibility
|
||||
const formats = {
|
||||
// Modern browsers: AVIF
|
||||
avif: await processor.getFromSmartfile(sourceImage, {
|
||||
format: 'avif',
|
||||
width: 1200
|
||||
}),
|
||||
|
||||
// Good browser support: WebP
|
||||
webp: await processor.getFromSmartfile(sourceImage, {
|
||||
format: 'webp',
|
||||
width: 1200
|
||||
}),
|
||||
|
||||
// Universal fallback: Progressive JPEG
|
||||
jpeg: await processor.getFromSmartfile(sourceImage, {
|
||||
format: 'jpeg',
|
||||
progressive: true,
|
||||
width: 1200
|
||||
})
|
||||
};
|
||||
|
||||
return formats;
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference 📚
|
||||
|
||||
### Constructor Options
|
||||
```typescript
|
||||
interface ISmartJimpOptions {
|
||||
mode: 'sharp' | 'jimp'; // Choose your processing engine
|
||||
}
|
||||
```
|
||||
|
||||
### Processing Options
|
||||
```typescript
|
||||
interface IAssetVariation {
|
||||
format?: 'avif' | 'webp' | 'png' | 'jpeg'; // Output format
|
||||
width?: number; // Target width (maintains aspect ratio if height not set)
|
||||
height?: number; // Target height (maintains aspect ratio if width not set)
|
||||
invert?: boolean; // Invert colors (jimp only currently)
|
||||
progressive?: boolean; // Create progressive JPEG (sharp only, jpeg format only)
|
||||
}
|
||||
```
|
||||
|
||||
### Main Methods
|
||||
|
||||
#### `getFromSmartfile(smartfile, options?)`
|
||||
Process a SmartFile instance with caching enabled.
|
||||
|
||||
#### `computeAssetVariation(buffer, options)`
|
||||
Process a raw buffer without caching.
|
||||
|
||||
#### `createAvifImageFromBuffer(buffer)`
|
||||
Create an AVIF image from buffer (sharp mode only).
|
||||
|
||||
## Performance Tips 🏎️
|
||||
|
||||
1. **Use Sharp mode in production** - It's significantly faster
|
||||
2. **Leverage the built-in cache** - Process identical images only once
|
||||
3. **Batch operations** - Use `Promise.all()` for concurrent processing
|
||||
4. **Choose appropriate formats**:
|
||||
- AVIF: Best compression, limited support
|
||||
- WebP: Good compression, good support
|
||||
- Progressive JPEG: Universal support, good perceived performance
|
||||
- PNG: Lossless, larger files
|
||||
|
||||
## Troubleshooting 🔧
|
||||
|
||||
### Sharp installation issues
|
||||
If you encounter issues with Sharp:
|
||||
```bash
|
||||
# Rebuild sharp from source
|
||||
npm rebuild sharp
|
||||
|
||||
# Or install with specific platform
|
||||
npm install sharp --platform=linux --arch=x64
|
||||
```
|
||||
|
||||
### Memory usage
|
||||
For processing many large images:
|
||||
```typescript
|
||||
// Process in batches to control memory usage
|
||||
const batchSize = 10;
|
||||
for (let i = 0; i < images.length; i += batchSize) {
|
||||
const batch = images.slice(i, i + batchSize);
|
||||
await processBatch(batch);
|
||||
}
|
||||
```
|
||||
|
||||
### Progressive JPEG verification
|
||||
To verify if a JPEG is progressive:
|
||||
```bash
|
||||
# Using ImageMagick
|
||||
identify -verbose image.jpg | grep "Interlace"
|
||||
# Output: "Interlace: JPEG" means progressive
|
||||
|
||||
# Using exiftool
|
||||
exiftool -EncodingProcess image.jpg
|
||||
```
|
||||
|
||||
## Contributing 🤝
|
||||
|
||||
We welcome contributions! Please feel free to submit a Pull Request.
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -102,4 +369,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
Reference in New Issue
Block a user