rustbasic-webp 0.0.5

High-performance WebP image conversion and optimization package for the RustBasic Framework.
Documentation
use rustbasic_core::webp::Encoder;
use rustbasic_core::image;
use rustbasic_core::serde::{Serialize, Deserialize};
use std::path::Path;
use std::fs;

/// Struct to store image metadata details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(crate = "rustbasic_core::serde")]
pub struct ImageInfo {
    pub width: u32,
    pub height: u32,
    pub format: String,
    pub size_bytes: usize,
}

/// Mendapatkan informasi metadata dari data gambar biner.
pub fn get_image_info(image_data: &[u8]) -> Result<ImageInfo, String> {
    let format = image::guess_format(image_data)
        .map_err(|e| format!("Gagal mendeteksi format gambar: {}", e))?;
    
    let img = image::load_from_memory(image_data)
        .map_err(|e| format!("Gagal memuat gambar untuk membaca info: {}", e))?;

    let format_str = format!("{:?}", format);

    Ok(ImageInfo {
        width: img.width(),
        height: img.height(),
        format: format_str,
        size_bytes: image_data.len(),
    })
}

/// Konversi gambar mentah (JPEG/PNG/dll) menjadi format WebP berkinerja tinggi.
pub fn convert_to_webp(image_data: &[u8], quality: f32) -> Result<Vec<u8>, String> {
    // Muat gambar menggunakan library 'image' yang murni ditulis dalam Rust
    let img = image::load_from_memory(image_data)
        .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;

    // Encode gambar ke format WebP menggunakan WebP encoder wrapper
    let encoder = Encoder::from_image(&img)
        .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
    
    let webp_memory = encoder.encode(quality);
    Ok(webp_memory.to_vec())
}

/// Konversi gambar mentah menjadi WebP dengan mengubah dimensi maksimal (resize) secara asimetris.
pub fn convert_and_resize(image_data: &[u8], max_width: u32, max_height: u32, quality: f32) -> Result<Vec<u8>, String> {
    let img = image::load_from_memory(image_data)
        .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;

    // Ubah ukuran gambar dengan tetap menjaga rasio aspek asli (Lanczos filter)
    let resized = img.resize(max_width, max_height, image::imageops::FilterType::Lanczos3);

    let encoder = Encoder::from_image(&resized)
        .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
    
    let webp_memory = encoder.encode(quality);
    Ok(webp_memory.to_vec())
}

/// Konversi gambar mentah menjadi WebP dengan mengubah lebar maksimal (resize width) menjaga aspek rasio.
pub fn convert_and_resize_width(image_data: &[u8], max_width: u32, quality: f32) -> Result<Vec<u8>, String> {
    let img = image::load_from_memory(image_data)
        .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;

    let resized = img.resize(max_width, u32::MAX, image::imageops::FilterType::Lanczos3);

    let encoder = Encoder::from_image(&resized)
        .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
    
    let webp_memory = encoder.encode(quality);
    Ok(webp_memory.to_vec())
}

/// Konversi gambar mentah menjadi WebP dengan mengubah tinggi maksimal (resize height) menjaga aspek rasio.
pub fn convert_and_resize_height(image_data: &[u8], max_height: u32, quality: f32) -> Result<Vec<u8>, String> {
    let img = image::load_from_memory(image_data)
        .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;

    let resized = img.resize(u32::MAX, max_height, image::imageops::FilterType::Lanczos3);

    let encoder = Encoder::from_image(&resized)
        .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
    
    let webp_memory = encoder.encode(quality);
    Ok(webp_memory.to_vec())
}

/// Konversi berkas lokal (JPEG/PNG/dll) langsung menjadi format WebP.
pub fn convert_file_to_webp<P: AsRef<Path>>(input_path: P, output_path: P, quality: f32) -> Result<(), String> {
    let data = fs::read(input_path).map_err(|e| format!("Gagal membaca file input: {}", e))?;
    let webp_data = convert_to_webp(&data, quality)?;
    fs::write(output_path, webp_data).map_err(|e| format!("Gagal menulis file output: {}", e))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustbasic_core::image::{ImageBuffer, Rgb};

    fn create_test_image_bytes() -> Vec<u8> {
        let img = ImageBuffer::from_fn(100, 100, |x, y| {
            if (x + y) % 2 == 0 {
                Rgb([255, 0, 0])
            } else {
                Rgb([0, 255, 0])
            }
        });
        let dynamic_img = image::DynamicImage::ImageRgb8(img);
        let mut cursor = std::io::Cursor::new(Vec::new());
        dynamic_img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
        cursor.into_inner()
    }

    #[test]
    fn test_convert_to_webp() {
        let png_bytes = create_test_image_bytes();
        let webp_bytes = convert_to_webp(&png_bytes, 80.0).unwrap();
        assert!(!webp_bytes.is_empty());

        let info = get_image_info(&webp_bytes).unwrap();
        assert_eq!(info.format, "WebP");
        assert_eq!(info.width, 100);
        assert_eq!(info.height, 100);
    }

    #[test]
    fn test_convert_and_resize() {
        let png_bytes = create_test_image_bytes();
        let webp_bytes = convert_and_resize(&png_bytes, 50, 50, 80.0).unwrap();
        let info = get_image_info(&webp_bytes).unwrap();
        assert_eq!(info.width, 50);
        assert_eq!(info.height, 50);
    }

    #[test]
    fn test_convert_and_resize_width() {
        let png_bytes = create_test_image_bytes();
        let webp_bytes = convert_and_resize_width(&png_bytes, 40, 80.0).unwrap();
        let info = get_image_info(&webp_bytes).unwrap();
        assert_eq!(info.width, 40);
        assert_eq!(info.height, 40); // 40x40 since aspect ratio of 100x100 is 1:1
    }

    #[test]
    fn test_convert_and_resize_height() {
        let png_bytes = create_test_image_bytes();
        let webp_bytes = convert_and_resize_height(&png_bytes, 30, 80.0).unwrap();
        let info = get_image_info(&webp_bytes).unwrap();
        assert_eq!(info.width, 30); // 30x30 since aspect ratio of 100x100 is 1:1
        assert_eq!(info.height, 30);
    }
}