Skip to content
TheChatArchiveThe Chat Archive
Metallama-4-maverick-03-26-experimental· MetaHugging Face LMArena Human Preference 140K

make a IMAGE COMPRESSION LIBRARY in RUST which will make any image to around 30 kb…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Mistralmistral-small-2506’s answer.
  1. User

    make a IMAGE COMPRESSION LIBRARY in RUST which will make any image to around 30 kb hardcoded when USER will import or DRAG-AND-DROPS THE IMAGE in app's dataset or database page,

  2. Meta Assistant

    What a fantastic project! Here's a comprehensive guide to creating an image compression library in Rust that compresses images to approximately 30KB. We'll use the following crates:

    1. image: for image processing and decoding/encoding
    2. mozjpeg: for JPEG compression ( Rust wrapper around MozJPEG, a JPEG encoder optimized for web)
    3. png: for PNG compression
    4. webp: for WebP compression (optional, but nice to have)
    5. winit and dnd (drag-n-drop): for handling file drag-and-drop (GUI event handling)
    6. rusqlite (optional): if you want to store compressed images in a SQLite database

    Step 1: Set up your Rust project

    Create a new Rust project using Cargo:

    cargo new image_compressor --bin
    

    Add the following dependencies to your Cargo.toml:

    [dependencies]
    image = "0.23.14"
    mozjpeg = "0.8.1"
    png = "0.16.3"
    webp = { version = "0.2.2", optional = true } # optional
    winit = "0.26.1" # for GUI event handling (drag-n-drop)
    dnd = "0.3.0" # for drag-n-drop functionality
    rusqlite = { version = "0.26.0", optional = true } # for SQLite database storage
    
    [features]
    webp_support = ["webp"] # optional feature
    db_storage = ["rusqlite"] # optional feature
    

    Step 2: Implement the image compression logic

    Create a new file src/compress.rs with the following code:

    use image::{GenericImageView, DynamicImage, ImageFormat};
    use mozjpeg::{Compress, ColorSpace};
    use png::{Encoder, Compression};
    use std::path::Path;
    use std::fs::File;
    use std::io::BufWriter;
    
    // Target file size (approx. 30KB)
    const TARGET_SIZE: u64 = 30 * 1024;
    
    // Compression settings (adjust these for quality/file size tradeoff)
    const JPEG_QUALITY: u8 = 70; // MozJPEG quality (1-100)
    const PNG_COMPRESSION: u8 = 6; // PNG compression level (0-9)
    const WEBP_QUALITY: f32 = 60.0; // WebP quality (1.0-100.0)
    
    pub enum CompressionFormat {
        JPEG,
        PNG,
        WebP, // optional
    }
    
    pub fn compress_image(input_path: &str, output_path: &str, format: CompressionFormat) -> Result<(), String> {
        let img = image::open(input_path).map_err(|e| e.to_string())?;
        let (width, height) = img.dimensions();
    
        match format {
            CompressionFormat::JPEG => compress_jpeg(img, output_path, width, height),
            CompressionFormat::PNG => compress_png(img, output_path, width, height),
            CompressionFormat::WebP => {
                #[cfg(feature = "webp_support")]
                compress_webp(img, output_path, width, height)
                    .map_err(|e| e.to_string())?;
                #[cfg(not(feature = "webp_support"))]
                Err("WebP support not enabled".to_string())
            }
        }
    }
    
    fn compress_jpeg(img: DynamicImage, output_path: &str, width: u32, height: u32) -> Result<(), String> {
        let mut compressor = Compress::new(ColorSpace::JCS_YCbCr);
        compressor.set_quality(JPEG_QUALITY);
        compressor.set_size(width, height);
    
        let mut file = BufWriter::new(File::create(output_path).unwrap());
        let mut data = Vec::new();
    
        compressor.compress(&img.to_rgb8().into_raw(), &mut data)
            .map_err(|e| e.to_string())?;
    
        // Write compressed data to file
        file.write_all(&data).map_err(|e| e.to_string())?;
    
        // Check file size and adjust quality if needed
        let file_size = std::fs::metadata(output_path).unwrap().len();
        if file_size > TARGET_SIZE {
            // Reduce quality and retry (simple approach, can be improved)
            compressor.set_quality(JPEG_QUALITY - 10);
            compressor.compress(&img.to_rgb8().into_raw(), &mut data)
                .map_err(|e| e.to_string())?;
            file.write_all(&data).map_err(|e| e.to_string())?;
        }
    
        Ok(())
    }
    
    fn compress_png(img: DynamicImage, output_path: &str, width: u32, height: u32) -> Result<(), String> {
        let file = File::create(output_path).unwrap();
        let mut encoder = Encoder::new(file, width, height);
        encoder.set_compression(Compression::new(PNG_COMPRESSION));
    
        // Encode image data
        let mut writer = encoder.write_header().unwrap();
        writer.write_image_data(&img.to_rgba8().into_raw())
            .map_err(|e| e.to_string())?;
    
        // Check file size and adjust compression if needed
        let file_size = std::fs::metadata(output_path).unwrap().len();
        if file_size > TARGET_SIZE {
            // Increase compression level and retry (simple approach, can be improved)
            encoder.set_compression(Compression::new(PNG_COMPRESSION + 2));
            writer.write_image_data(&img.to_rgba8().into_raw())
                .map_err(|e| e.to_string())?;
        }
    
        Ok(())
    }
    
    #[cfg(feature = "webp_support")]
    fn compress_webp(img: DynamicImage, output_path: &str, width: u32, height: u32) -> Result<(), webp::Error> {
        let mut encoder = webp::Encoder::from_image(&img.to_rgba8())?;
        encoder.set_quality(WEBP_QUALITY);
        let data = encoder.encode()?;
    
        // Write compressed data to file
        std::fs::write(output_path, &data)?;
    
        // Check file size and adjust quality if needed
        let file_size = std::fs::metadata(output_path).unwrap().len();
        if file_size > TARGET_SIZE {
            // Reduce quality and retry (simple approach, can be improved)
            encoder.set_quality(WEBP_QUALITY - 10.0);
            let data = encoder.encode()?;
            std::fs::write(output_path, &data)?;
        }
    
        Ok(())
    }
    

    This code defines:

    1. compress_image: the main function that takes an input image path, output path, and desired compression format (JPEG, PNG, or WebP).
    2. compress_jpeg, compress_png, and compress_webp: format-specific compression functions that:
      • Open the input image using image.
      • Compress the image data using the respective encoder (MozJPEG, PNG, or WebP).
      • Write the compressed data to the output file.
      • Check the resulting file size and adjust compression settings (quality or compression level) if the file size exceeds the target (~30KB).

    Step 3: Handle drag-and-drop and file import

    Create a new file src/gui.rs with the following code:

    use winit::{
        event::{Event, WindowEvent},
        event_loop::{ControlFlow, EventLoop},
        window::WindowBuilder,
    };
    use dnd::{DropData, DropHandler};
    use std::path::PathBuf;
    
    pub struct ImageCompressorApp {
        event_loop: EventLoop<()>,
        window: winit::window::Window,
    }
    
    impl ImageCompressorApp {
        pub fn new() -> Self {
            let event_loop = EventLoop::new();
            let window = WindowBuilder::new()
                .with_title("Image Compressor")
                .build(&event_loop)
                .unwrap();
    
            Self { event_loop, window }
        }
    
        pub fn run(&mut self) {
            let mut drop_handler = DropHandler::new();
            drop_handler.set_callback(move |data: DropData| {
                if let Some(file_path) = data.file_path {
                    // Handle dropped file
                    handle_dropped_file(file_path);
                }
            });
    
            self.event_loop.run(move |event, _, control_flow| {
                *control_flow = ControlFlow::Wait;
    
                match event {
                    Event::WindowEvent { event, .. } => match event {
                        WindowEvent::DroppedFile(file_path) => {
                            drop_handler.handle_drop(file_path);
                        }
                        _ => (),
                    },
                    _ => (),
                }
            });
        }
    }
    
    fn handle_dropped_file(file_path: PathBuf) {
        // Get file extension (determine compression format)
        let ext = file_path.extension().unwrap().to_str().unwrap();
        let format = match ext {
            "jpg" | "jpeg" => CompressionFormat::JPEG,
            "png" => CompressionFormat::PNG,
            "webp" => CompressionFormat::WebP,
            _ => {
                eprintln!("Unsupported file format: {}", ext);
                return;
            }
        };
    
        // Compress image
        let output_path = format!("compressed_{}", file_path.file_name().unwrap());
        compress_image(file_path.to_str().unwrap(), output_path, format)
            .unwrap_or_else(|e| eprintln!("Error compressing image: {}", e));
    }
    

    This code sets up a simple GUI window using winit and handles drag-and-drop events using dnd. When a file is dropped, it:

    1. Determines the compression format based on the file extension.
    2. Calls compress_image to compress the image.

    Step 4: Optional - Store compressed images in a SQLite database

    If you want to store the compressed images in a SQLite database, create a new file src/db.rs with the following code:

    use rusqlite::{Connection, params};
    
    pub fn store_compressed_image(db_path: &str, image_path: &str) -> Result<(), rusqlite::Error> {
        let conn = Connection::open(db_path)?;
    
        // Create table if not exists
        conn.execute_batch("
            CREATE TABLE IF NOT EXISTS compressed_images (
                id INTEGER PRIMARY KEY,
                image_data BLOB NOT NULL
            );
        ")?;
    
        // Read compressed image data
        let image_data = std::fs::read(image_path)?;
    
        // Insert into database
        conn.execute("
            INSERT INTO compressed_images (image_data) VALUES (?1);
        ", params![image_data])?;
    
        Ok(())
    }
    

    Then, modify the handle_dropped_file function in src/gui.rs to store the compressed image in the database:

    fn handle_dropped_file(file_path: PathBuf) {
        // ... (rest of the code remains the same)
    
        // Compress image
        let output_path = format!("compressed_{}", file_path.file_name().unwrap());
        compress_image(file_path.to_str().unwrap(), output_path, format)
            .unwrap_or_else(|e| eprintln!("Error compressing image: {}", e));
    
        // Store compressed image in database (optional)
        #[cfg(feature = "db_storage")]
        store_compressed_image("image_db.sqlite", output_path)
            .unwrap_or_else(|e| eprintln!("Error storing image in database: {}", e));
    }
    

    Final steps

    1. In your src/main.rs, import and run the GUI app:
    mod compress;
    mod gui;
    
    fn main() {
        let mut app = gui::ImageCompressorApp::new();
        app.run();
    }
    
    1. Build and run your project:
    cargo run
    
    1. Drag-and-drop an image file onto the GUI window. The image will be compressed and saved as a new file (e.g., compressed_image.jpg). If you've enabled database storage, the compressed image will also be stored in the SQLite database.

    Features and limitations

    • Supports JPEG, PNG, and WebP (optional) compression formats.
    • Simple quality/compression level adjustment to reach the target file size (~30KB).
    • Drag-and-drop GUI using winit and dnd.
    • Optional SQLite database storage using rusqlite.

    Limitations:

    • No error diffusion or dithering for JPEG compression ( MozJPEG doesn't support it).
    • No advanced compression settings (e.g., chroma subsampling, quantization tables).
    • No multi-threading or parallel compression.
    • Database storage is a simple example; you'll likely want to improve the schema and error handling.

    That's it! You've created a functional image compression library in Rust with a GUI for drag-and-drop functionality. Happy compressing!

    Future improvements

    • Add more advanced compression settings and algorithms (e.g., Guetzli, AVIF).
    • Implement multi-threading or parallel compression for large images.
    • Enhance the GUI with image previews, compression settings, and file management.
    • Improve database storage with better schema design, indexing, and querying.
    • Explore WebAssembly (WASM) compilation for web-based image compression.

    The Rust ecosystem is vast and exciting! Keep exploring and building amazing projects!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.