size_ranged_image_compressor
A Dart package for compressing image files to fit within a specified size range, while maintaining the best possible quality. Features
- Compress images to fit within a specified size range (minimum and maximum file size)
- Maintains the highest possible quality while meeting size constraints
- Handles both resizing and quality adjustment for optimal results
- Provides clear error messages if compression fails
Installation
Add this to your package's pubspec.yaml file:
dependencies:
size_ranged_image_compressor: ^1.0.0
Then run:
$ flutter pub get
Usage
Here's a simple example of how to use the size_ranged_image_compressor:
import 'dart:io';
import 'package:size_ranged_image_compressor/size_ranged_image_compressor.dart';
void main() async {
File imageFile = File('path/to/your/image.jpg');
var result = await ImageCompressor.compressSingleFileWithCustomSize(
imageFile,
minimum: 50 * 1024, // 50 KB
maximum: 200 * 1024, // 200 KB
);
result.fold(
(error) => print('Compression failed: $error'),
(compressedFile) => print('Compressed file size: ${compressedFile.lengthSync()} bytes'),
);
}
This example demonstrates how to compress an image file to a size between 50 KB and 200 KB.
API Reference
ImageCompressor.compressSingleFileWithCustomSize
static Future
Compresses a single image file to fit within a specified size range.
Parameters:
- file: The original image file to be compressed. Must be a valid image file.
- minimum: The minimum allowed file size in bytes. Must be greater than 0 and less than or equal to maximum.
- maximum: The maximum allowed file size in bytes. Must be greater than or equal to minimum.
- qualityStep: The step size for reducing quality during compression. Default is 2. Lower values result in more gradual quality reduction.
Returns:
An Either containing either an error message (String) if compression fails, or the compressed File if successful.
Throws:
ArgumentError if maximum is less than minimum.
Error Handling
The package uses the Either type for error handling. If compression fails, it will return a Left with an error message. If successful, it will return a Right with the compressed File.
Common error messages include:
- "File is smaller than the minimum size requirement"
- "Compression failed"
- "Unable to compress file to desired size range"
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the BSD 2-Clause License - see the LICENSE file for details.