1use webp::Encoder;
2use serde::{Serialize, Deserialize};
3use std::path::Path;
4use std::fs;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct ImageInfo {
9 pub width: u32,
10 pub height: u32,
11 pub format: String,
12 pub size_bytes: usize,
13}
14
15pub fn get_image_info(image_data: &[u8]) -> Result<ImageInfo, String> {
17 let format = image::guess_format(image_data)
18 .map_err(|e| format!("Gagal mendeteksi format gambar: {}", e))?;
19
20 let img = image::load_from_memory(image_data)
21 .map_err(|e| format!("Gagal memuat gambar untuk membaca info: {}", e))?;
22
23 let format_str = format!("{:?}", format);
24
25 Ok(ImageInfo {
26 width: img.width(),
27 height: img.height(),
28 format: format_str,
29 size_bytes: image_data.len(),
30 })
31}
32
33pub fn convert_to_webp(image_data: &[u8], quality: f32) -> Result<Vec<u8>, String> {
35 let img = image::load_from_memory(image_data)
37 .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;
38
39 let encoder = Encoder::from_image(&img)
41 .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
42
43 let webp_memory = encoder.encode(quality);
44 Ok(webp_memory.to_vec())
45}
46
47pub fn convert_and_resize(image_data: &[u8], max_width: u32, max_height: u32, quality: f32) -> Result<Vec<u8>, String> {
49 let img = image::load_from_memory(image_data)
50 .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;
51
52 let resized = img.resize(max_width, max_height, image::imageops::FilterType::Lanczos3);
54
55 let encoder = Encoder::from_image(&resized)
56 .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
57
58 let webp_memory = encoder.encode(quality);
59 Ok(webp_memory.to_vec())
60}
61
62pub fn convert_and_resize_width(image_data: &[u8], max_width: u32, quality: f32) -> Result<Vec<u8>, String> {
64 let img = image::load_from_memory(image_data)
65 .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;
66
67 let resized = img.resize(max_width, u32::MAX, image::imageops::FilterType::Lanczos3);
68
69 let encoder = Encoder::from_image(&resized)
70 .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
71
72 let webp_memory = encoder.encode(quality);
73 Ok(webp_memory.to_vec())
74}
75
76pub fn convert_and_resize_height(image_data: &[u8], max_height: u32, quality: f32) -> Result<Vec<u8>, String> {
78 let img = image::load_from_memory(image_data)
79 .map_err(|e| format!("Gagal memuat gambar dari memori: {}", e))?;
80
81 let resized = img.resize(u32::MAX, max_height, image::imageops::FilterType::Lanczos3);
82
83 let encoder = Encoder::from_image(&resized)
84 .map_err(|e| format!("Gagal menginisialisasi encoder WebP: {:?}", e))?;
85
86 let webp_memory = encoder.encode(quality);
87 Ok(webp_memory.to_vec())
88}
89
90pub fn convert_file_to_webp<P: AsRef<Path>>(input_path: P, output_path: P, quality: f32) -> Result<(), String> {
92 let data = fs::read(input_path).map_err(|e| format!("Gagal membaca file input: {}", e))?;
93 let webp_data = convert_to_webp(&data, quality)?;
94 fs::write(output_path, webp_data).map_err(|e| format!("Gagal menulis file output: {}", e))?;
95 Ok(())
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101 use image::{ImageBuffer, Rgb};
102
103 fn create_test_image_bytes() -> Vec<u8> {
104 let img = ImageBuffer::from_fn(100, 100, |x, y| {
105 if (x + y) % 2 == 0 {
106 Rgb([255, 0, 0])
107 } else {
108 Rgb([0, 255, 0])
109 }
110 });
111 let dynamic_img = image::DynamicImage::ImageRgb8(img);
112 let mut cursor = std::io::Cursor::new(Vec::new());
113 dynamic_img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
114 cursor.into_inner()
115 }
116
117 #[test]
118 fn test_convert_to_webp() {
119 let png_bytes = create_test_image_bytes();
120 let webp_bytes = convert_to_webp(&png_bytes, 80.0).unwrap();
121 assert!(!webp_bytes.is_empty());
122
123 let info = get_image_info(&webp_bytes).unwrap();
124 assert_eq!(info.format, "WebP");
125 assert_eq!(info.width, 100);
126 assert_eq!(info.height, 100);
127 }
128
129 #[test]
130 fn test_convert_and_resize() {
131 let png_bytes = create_test_image_bytes();
132 let webp_bytes = convert_and_resize(&png_bytes, 50, 50, 80.0).unwrap();
133 let info = get_image_info(&webp_bytes).unwrap();
134 assert_eq!(info.width, 50);
135 assert_eq!(info.height, 50);
136 }
137
138 #[test]
139 fn test_convert_and_resize_width() {
140 let png_bytes = create_test_image_bytes();
141 let webp_bytes = convert_and_resize_width(&png_bytes, 40, 80.0).unwrap();
142 let info = get_image_info(&webp_bytes).unwrap();
143 assert_eq!(info.width, 40);
144 assert_eq!(info.height, 40); }
146
147 #[test]
148 fn test_convert_and_resize_height() {
149 let png_bytes = create_test_image_bytes();
150 let webp_bytes = convert_and_resize_height(&png_bytes, 30, 80.0).unwrap();
151 let info = get_image_info(&webp_bytes).unwrap();
152 assert_eq!(info.width, 30); assert_eq!(info.height, 30);
154 }
155}
156