update code level
This commit is contained in:
@@ -80,6 +80,44 @@ impl ImageProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/// 快速生成缩略图(低质量但快速)
|
||||
pub async fn generate_fast_thumbnail(&self, image_data: &[u8], _filename: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
// 使用快速解码和缩放
|
||||
let img = image::load_from_memory(image_data)?;
|
||||
|
||||
// 快速缩放到小尺寸(200x150)
|
||||
let thumbnail = img.thumbnail(200, 150);
|
||||
|
||||
// 使用低质量JPEG压缩以加快编码速度
|
||||
let mut output = Vec::new();
|
||||
thumbnail.write_to(&mut std::io::Cursor::new(&mut output), image::ImageOutputFormat::Jpeg(50))?;
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// 快速调整图片尺寸(最大宽度)
|
||||
pub async fn resize_image_to_max(&self, image_data: &[u8], max_width: u32) -> Vec<u8> {
|
||||
match image::load_from_memory(image_data) {
|
||||
Ok(img) => {
|
||||
let (width, height) = img.dimensions();
|
||||
if width <= max_width {
|
||||
return image_data.to_vec(); // 无需调整
|
||||
}
|
||||
|
||||
let new_height = (height as f32 * max_width as f32 / width as f32) as u32;
|
||||
let resized = img.thumbnail(max_width, new_height);
|
||||
|
||||
let mut output = Vec::new();
|
||||
if resized.write_to(&mut std::io::Cursor::new(&mut output), image::ImageOutputFormat::Jpeg(75)).is_ok() {
|
||||
output
|
||||
} else {
|
||||
image_data.to_vec() // 失败时返回原图
|
||||
}
|
||||
}
|
||||
Err(_) => image_data.to_vec(), // 解码失败时返回原图
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_image_url(&self, filename: &str) -> String {
|
||||
format!("/images/{}", filename)
|
||||
}
|
||||
@@ -128,7 +166,7 @@ impl ImageProcessor {
|
||||
let img = image::load_from_memory(image_data)?;
|
||||
|
||||
// 生成缩略图(400x300,保持宽高比)
|
||||
let thumbnail = img.thumbnail(400, 300);
|
||||
let thumbnail = img.thumbnail(600, 400);
|
||||
|
||||
// 将缩略图数据保存到内存缓冲区
|
||||
let mut buffer = std::io::Cursor::new(Vec::new());
|
||||
|
||||
Reference in New Issue
Block a user