ngx-image-manager-engine
v1.0.1
Published
An intelligent Angular library for image compression and cropping with adaptive quality reduction algorithm
Downloads
16
Maintainers
Readme
🖼️ NGX Image Manager Engine
An intelligent Angular library for image compression and cropping with adaptive quality reduction algorithm.
✨ Features
- 🎯 Smart Compression: Adaptive quality reduction algorithm that intelligently adjusts compression based on file size
- ✂️ Image Cropping: Full-featured cropper with rotation, zoom, and aspect ratio controls
- 📱 Responsive UI: Beautiful modal interface with Persian (RTL) support
- 🚀 Performance: Optimized for large images (handles files up to 50MB+)
- 📊 Progress Tracking: Real-time compression progress with detailed attempt information
- 🎨 Customizable: Extensive configuration options for both compression and cropping
- 💪 TypeScript: Full type safety with comprehensive interfaces
- 🌐 i18n Ready: Easy localization support (currently Persian)
- 🔄 Error Recovery: Built-in retry mechanism and camera fallback
- 📦 Standalone: Works independently without external dependencies (except peer deps)
📦 Installation
npm install ngx-image-manager-enginePeer Dependencies
Install the required peer dependencies:
npm install @angular/common @angular/core
npm install @acorex/components
npm install angular-cropperjs
npm install ngx-image-compress🚀 Quick Start
1. Import the Service
import { Component } from '@angular/core';
import { ImageCompressorEngineService } from 'ngx-image-manager-engine';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [ImageCompressorEngineService] // Add service to providers
})
export class AppComponent {
constructor(private compressor: ImageCompressorEngineService) {}
}2. Use the Service
async compressImage(file: File) {
const result = await this.compressor.imageCompressorEngine({
imageData: file,
options: {
maxSizeInBytes: 500000, // 500KB
cropperOption: {
aspectRatio: 1, // Square crop
rotatable: true
}
}
});
if (result) {
console.log('Compressed image (Base64):', result);
// Use the compressed image...
}
}3. Handle File Input
onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files && input.files[0]) {
this.compressImage(input.files[0]);
}
}<input type="file" accept="image/*" (change)="onFileSelected($event)">📚 API Documentation
imageCompressorEngine(config: IImageCompressor): Promise<string | undefined>
Main method to compress and/or crop images.
Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| imageData | File \| string | ✅ | Image file or base64 string |
| options | IImageCompressorOptions | ❌ | Configuration options |
Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| maxSizeInBytes | number | 512000 | Maximum file size in bytes (500KB default) |
| maxSizeInKbAllowedForUI | number | - | Display-only max size for UI |
| skipCompressor | boolean | false | Skip compression step (crop only) |
| skipCropper | boolean | false | Skip cropping step (compress only) |
| cropperOption | ICropperOptions | {} | Cropper configuration (see below) |
| titleText | string | - | Custom modal title |
| showUploadInfo | boolean | true | Show size information in UI |
Cropper Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| viewMode | 0 \| 1 \| 2 \| 3 | 1 | Cropper view mode |
| aspectRatio | number | - | Aspect ratio (e.g., 1 for square, 16/9 for wide) |
| rotatable | boolean | false | Enable rotation controls |
| movable | boolean | true | Enable image movement |
| zoomable | boolean | true | Enable zoom |
| scalable | boolean | true | Enable scaling |
| autoCropArea | number | 1 | Auto crop area size (0-1) |
| cropBoxResizable | boolean | true | Allow crop box resizing |
| cropBoxMovable | boolean | true | Allow crop box movement |
🎯 Usage Examples
Example 1: Basic Compression
const compressed = await this.compressor.imageCompressorEngine({
imageData: selectedFile,
options: {
maxSizeInBytes: 300000 // 300KB
}
});Example 2: Square Crop with Rotation
const cropped = await this.compressor.imageCompressorEngine({
imageData: selectedFile,
options: {
maxSizeInBytes: 500000,
cropperOption: {
aspectRatio: 1, // Square
rotatable: true,
viewMode: 1
}
}
});Example 3: Crop Only (No Compression)
const result = await this.compressor.imageCompressorEngine({
imageData: selectedFile,
options: {
skipCompressor: true, // Skip compression
cropperOption: {
aspectRatio: 16 / 9, // Wide format
rotatable: true
}
}
});Example 4: Compress Only (No Cropping)
const result = await this.compressor.imageCompressorEngine({
imageData: selectedFile,
options: {
skipCropper: true, // Skip cropping
maxSizeInBytes: 200000 // 200KB
}
});Example 5: From Base64 String
const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
const result = await this.compressor.imageCompressorEngine({
imageData: base64Image,
options: {
maxSizeInBytes: 400000
}
});Example 6: Custom Title and UI
const result = await this.compressor.imageCompressorEngine({
imageData: selectedFile,
options: {
titleText: 'تنظیم تصویر پروفایل',
maxSizeInBytes: 300000,
maxSizeInKbAllowedForUI: 300,
showUploadInfo: true,
cropperOption: {
aspectRatio: 1,
rotatable: true
}
}
});🧠 Smart Compression Algorithm
The library uses an intelligent adaptive compression algorithm:
How It Works
Size Analysis: Analyzes the ratio between original and target file size
Quality Strategy: Determines optimal starting quality based on size ratio:
- Files 50x larger: Start at 60% quality
- Files 20x larger: Start at 75% quality
- Files 10x larger: Start at 85% quality
- Others: Start at 100% quality
Adaptive Reduction: Dynamically adjusts quality per iteration:
- Close to target (≤1.5x): Reduce by 5%
- Far from target (≥10x): Reduce by up to 60%
- Progressive reduction for intermediate sizes
Progress Tracking: Shows real-time compression attempts with:
- Current file size
- Quality used
- Success/failure status
- Reduction percentage
Example Output
تلاش 1: حجم نهایی 450 KB - غیرمجاز
تلاش 2: حجم نهایی 380 KB - غیرمجاز
تلاش 3: حجم نهایی 280 KB - مجاز ✓🎨 UI Features
Modal Interface
- Loading State: Skeleton loader during initial processing
- Cropper View: Interactive cropper with rotation controls
- Compression Progress: Real-time progress bars for each attempt
- Error Handling: User-friendly error messages with retry options
- Camera Fallback: Option to use device camera if image fails to load
Responsive Design
- Mobile-optimized interface
- Touch-friendly controls
- RTL (Right-to-Left) support for Persian
- Dark mode compatible
🌐 Browser Support
- ✅ Chrome (latest)
- ✅ Firefox (latest)
- ✅ Safari (latest)
- ✅ Edge (latest)
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)
🔧 Advanced Configuration
Complete Configuration Example
const result = await this.compressor.imageCompressorEngine({
imageData: file,
options: {
// Compression settings
maxSizeInBytes: 512000,
maxSizeInKbAllowedForUI: 500,
skipCompressor: false,
// Cropper settings
skipCropper: false,
cropperOption: {
viewMode: 1,
dragMode: 'move',
aspectRatio: 16 / 9,
autoCropArea: 1,
movable: true,
rotatable: true,
scalable: true,
zoomable: true,
zoomOnWheel: true,
wheelZoomRatio: 0.1,
cropBoxMovable: true,
cropBoxResizable: true,
toggleDragModeOnDblclick: true,
minCropBoxWidth: 100,
minCropBoxHeight: 100,
guides: true,
center: true,
highlight: true,
background: true,
modal: true
},
// UI settings
titleText: 'ویرایش تصویر',
showUploadInfo: true
}
});📖 Type Definitions
interface IImageCompressor {
imageData: Blob | string;
options?: IImageCompressorOptions;
}
interface IImageCompressorOptions {
maxSizeInBytes?: number;
maxSizeInKbAllowedForUI?: number;
cropperOption?: ICropperOptions;
skipCompressor?: boolean;
skipCropper?: boolean;
titleText?: string;
showUploadInfo?: boolean;
}
interface ICropperOptions {
viewMode?: 0 | 1 | 2 | 3;
dragMode?: 'crop' | 'move' | 'none';
aspectRatio?: number;
// ... (see full interface in source)
}🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
# Clone the repository
git clone https://github.com/rasa-salamat/ngx-image-manager-engine.git
# Install dependencies
cd ngx-image-manager-engine
npm install
# Build the library
npm run build
# Test locally
npm link📄 License
MIT © me.ghobadi
🐛 Issues
Found a bug? Open an issue
⭐ Support
If you like this project, please give it a star on GitHub!
📞 Contact
- Email: [email protected]
- GitHub: @me-ghobadi
🙏 Acknowledgments
- Built with Angular
- UI Components by Acorex
- Cropping powered by CropperJS
- Compression powered by ngx-image-compress
Made with ❤️ by me.ghobadi
