Rust Image Compression Library
Here's a Rust library that compresses images to approximately 30KB when they're imported or dragged into an application. This implementation uses the image crate for image processing and provides a simple API for compression.
Library Implementation
// src/lib.rs
use image::{DynamicImage, ImageError, ImageFormat};
use std::path::Path;
use std::io::Cursor;
/// Compresses an image to approximately 30KB
pub fn compress_image_to_30kb(
image_path: &Path,
output_path: &Path,
quality: u8,
) -> Result<(), ImageError> {
// Open the original image
let img = image::open(image_path)?;
// Convert to RGB if needed (for consistent processing)
let img = img.to_rgb8();
// Calculate initial size
let mut img_bytes = Vec::new();
img.write_to(&mut Cursor::new(&mut img_bytes), ImageFormat::Jpeg(quality))?;
// Adjust quality if needed to reach target size
let target_size = 30 * 1024; // 30KB
let mut current_quality = quality;
if img_bytes.len() > target_size {
// Binary search to find optimal quality
let mut low = 1;
let mut high = 100;
while low <= high {
let mid = (low + high) / 2;
let mut test_bytes = Vec::new();
img.write_to(&mut Cursor::new(&mut test_bytes), ImageFormat::Jpeg(mid))?;
if test_bytes.len() > target_size {
high = mid - 1;
} else {
current_quality = mid;
low = mid + 1;
}
}
}
// Save the compressed image
img.save_with_format(output_path, ImageFormat::Jpeg(current_quality))?;
Ok(())
}
/// Compresses an image from bytes to approximately 30KB
pub fn compress_image_bytes_to_30kb(
image_bytes: &[u8],
output_path: &Path,
quality: u8,
) -> Result<(), ImageError> {
let img = image::load_from_memory(image_bytes)?;
compress_image_to_30kb(&img, output_path, quality)
}
/// Compresses an image to bytes with approximately 30KB size
pub fn compress_image_to_30kb_bytes(
image_path: &Path,
quality: u8,
) -> Result<Vec<u8>, ImageError> {
let img = image::open(image_path)?;
let mut img_bytes = Vec::new();
// Calculate initial size
img.write_to(&mut Cursor::new(&mut img_bytes), ImageFormat::Jpeg(quality))?;
// Adjust quality if needed to reach target size
let target_size = 30 * 1024; // 30KB
let mut current_quality = quality;
if img_bytes.len() > target_size {
// Binary search to find optimal quality
let mut low = 1;
let mut high = 100;
while low <= high {
let mid = (low + high) / 2;
let mut test_bytes = Vec::new();
img.write_to(&mut Cursor::new(&mut test_bytes), ImageFormat::Jpeg(mid))?;
if test_bytes.len() > target_size {
high = mid - 1;
} else {
current_quality = mid;
low = mid + 1;
}
}
// Save with final quality
img_bytes.clear();
img.write_to(&mut Cursor::new(&mut img_bytes), ImageFormat::Jpeg(current_quality))?;
}
Ok(img_bytes)
}
Example Usage
Here's how you might use this library in an application:
// src/main.rs
use image_compression_lib::{compress_image_to_30kb, compress_image_to_30kb_bytes};
use std::path::Path;
fn main() {
// Example 1: Compress an image file to 30KB and save to new file
let input_path = Path::new("input.jpg");
let output_path = Path::new("output.jpg");
match compress_image_to_30kb(input_path, output_path, 85) {
Ok(_) => println!("Image compressed successfully!"),
Err(e) => eprintln!("Error compressing image: {}", e),
}
// Example 2: Get compressed image bytes
let input_path = Path::new("input.png");
match compress_image_to_30kb_bytes(input_path, 85) {
Ok(bytes) => {
println!("Compressed image size: {} bytes", bytes.len());
// You can now store these bytes in your database
},
Err(e) => eprintln!("Error compressing image: {}", e),
}
}
Cargo.toml
[package]
name = "image_compression_lib"
version = "0.1.0"
edition = "2021"
[dependencies]
image = "0.24.7"
Features
- File-based compression: Compresses an image file to approximately 30KB
- Byte-based compression: Compresses image bytes to approximately 30KB
- Quality adjustment: Uses binary search to find optimal JPEG quality for target size
- Format conversion: Handles various input formats (JPEG, PNG, etc.) and outputs JPEG
Integration with a Web App
For a web application where users can drag and drop images, you would:
- Accept the file in your frontend
- Send it to your Rust backend
- Use this library to compress it
- Store the compressed version in your database
The library provides both file and byte-based operations to support different use cases.
Notes
- The actual compressed size might vary slightly around 30KB due to the nature of JPEG compression
- For better compression, you might want to add additional preprocessing like resizing to a maximum dimension
- The quality parameter (default 85) is a starting point for the binary search
Would you like me to add any additional features to this library, such as resizing before compression or support for different output formats?