update code level

This commit is contained in:
lychang
2026-03-23 02:38:17 +08:00
parent 743d23cfee
commit 4115c04107
8 changed files with 662 additions and 95 deletions

View File

@@ -37,7 +37,7 @@ impl ImageProcessor {
// 生成缩略图
let thumbnail_path = self.config.thumbnails_dir.join(format!("thumb_{}", new_filename));
self.generate_thumbnail(&img, &thumbnail_path, 300, 200)?;
self.generate_thumbnail(&img, &thumbnail_path, 0, 0)?;
Ok(ImageInfo {
id: image_id,
@@ -49,24 +49,22 @@ impl ImageProcessor {
})
}
/// 生成缩略图并保存到指定路径(使用统一尺寸)
pub fn generate_thumbnail(
&self,
img: &image::DynamicImage,
output_path: &Path,
max_width: u32,
max_height: u32,
_max_width: u32,
_max_height: u32,
) -> Result<(), Box<dyn std::error::Error>> {
let (width, height) = img.dimensions();
// 计算缩略图尺寸
let ratio = width as f32 / height as f32;
let (new_width, new_height) = if width > height {
(max_width, (max_width as f32 / ratio) as u32)
} else {
((max_height as f32 * ratio) as u32, max_height)
};
let thumbnail = img.thumbnail(new_width, new_height);
// 使用统一的缩略图尺寸(400x300,保持宽高比)
let thumbnail = img.thumbnail(400, 300);
// 确保输出目录存在
if let Some(parent) = output_path.parent() {
fs::create_dir_all(parent)?;
}
thumbnail.save_with_format(output_path, ImageFormat::Jpeg)?;
Ok(())
@@ -100,6 +98,44 @@ impl ImageProcessor {
self.save_image(&image_data, filename).await
}
/// 从图片数据生成缩略图并保存到文件
pub async fn generate_thumbnail_from_data(
&self,
image_data: &[u8],
thumbnail_filename: &str,
) -> Result<(), Box<dyn std::error::Error>> {
// 使用统一的缩略图生成方法
let thumbnail_data = self.generate_thumbnail_from_memory(image_data, thumbnail_filename).await?;
// 确保缩略图目录存在
fs::create_dir_all(&self.config.thumbnails_dir)?;
// 保存缩略图到文件
let thumbnail_path = self.config.thumbnails_dir.join(thumbnail_filename);
fs::write(&thumbnail_path, thumbnail_data)?;
Ok(())
}
/// 从内存中的图片数据生成缩略图数据(不保存到文件)
pub async fn generate_thumbnail_from_memory(
&self,
image_data: &[u8],
_thumbnail_filename: &str,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
// 加载图片
let img = image::load_from_memory(image_data)?;
// 生成缩略图(400x300,保持宽高比)
let thumbnail = img.thumbnail(400, 300);
// 将缩略图数据保存到内存缓冲区
let mut buffer = std::io::Cursor::new(Vec::new());
thumbnail.write_to(&mut buffer, ImageFormat::Jpeg)?;
Ok(buffer.into_inner())
}
}
#[derive(Debug)]