update code level
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
use std::path::Path;
|
||||
use std::fs;
|
||||
use image::{GenericImageView, ImageFormat};
|
||||
use uuid::Uuid;
|
||||
use crate::config::StorageConfig;
|
||||
use image::{GenericImageView, ImageFormat};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ImageProcessorError {
|
||||
@@ -18,7 +18,10 @@ pub enum ImageProcessorError {
|
||||
// 手动实现 From<reqwest::Error> 以支持 ? 操作符
|
||||
impl From<reqwest::Error> for ImageProcessorError {
|
||||
fn from(err: reqwest::Error) -> Self {
|
||||
ImageProcessorError::Io(std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))
|
||||
ImageProcessorError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +44,11 @@ impl ImageProcessor {
|
||||
Self { config }
|
||||
}
|
||||
|
||||
pub async fn save_image(&self, image_data: &[u8], filename: &str) -> Result<ImageInfo, ImageProcessorError> {
|
||||
pub async fn save_image(
|
||||
&self,
|
||||
image_data: &[u8],
|
||||
filename: &str,
|
||||
) -> Result<ImageInfo, ImageProcessorError> {
|
||||
let image_id = Uuid::new_v4();
|
||||
let file_extension = Path::new(filename)
|
||||
.extension()
|
||||
@@ -60,7 +67,10 @@ impl ImageProcessor {
|
||||
let file_size = image_data.len() as i64;
|
||||
|
||||
// 生成缩略图
|
||||
let thumbnail_path = self.config.thumbnails_dir.join(format!("thumb_{}", new_filename));
|
||||
let thumbnail_path = self
|
||||
.config
|
||||
.thumbnails_dir
|
||||
.join(format!("thumb_{}", new_filename));
|
||||
self.generate_thumbnail(&img, &thumbnail_path, 0, 0)?;
|
||||
|
||||
Ok(ImageInfo {
|
||||
@@ -83,12 +93,12 @@ impl ImageProcessor {
|
||||
) -> Result<(), ImageProcessorError> {
|
||||
// 使用统一的缩略图尺寸(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(())
|
||||
@@ -104,21 +114,6 @@ impl ImageProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/// 快速生成缩略图(低质量但快速)
|
||||
pub async fn generate_fast_thumbnail(&self, image_data: &[u8], _filename: &str) -> Result<Vec<u8>, ImageProcessorError> {
|
||||
// 使用快速解码和缩放
|
||||
let img = image::load_from_memory(image_data)?;
|
||||
|
||||
// 快速缩放到小尺寸(200x200)
|
||||
let thumbnail = img.thumbnail(200, 200);
|
||||
|
||||
// 使用低质量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) {
|
||||
@@ -127,12 +122,18 @@ impl ImageProcessor {
|
||||
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() {
|
||||
if resized
|
||||
.write_to(
|
||||
&mut std::io::Cursor::new(&mut output),
|
||||
image::ImageOutputFormat::Jpeg(75),
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
output
|
||||
} else {
|
||||
image_data.to_vec() // 失败时返回原图
|
||||
@@ -146,10 +147,6 @@ impl ImageProcessor {
|
||||
format!("/images/{}", filename)
|
||||
}
|
||||
|
||||
pub fn get_thumbnail_url(&self, filename: &str) -> String {
|
||||
format!("/thumbnails/thumb_{}", filename)
|
||||
}
|
||||
|
||||
pub async fn download_and_save_image(
|
||||
&self,
|
||||
url: &str,
|
||||
@@ -161,42 +158,23 @@ impl ImageProcessor {
|
||||
self.save_image(&image_data, filename).await
|
||||
}
|
||||
|
||||
/// 从图片数据生成缩略图并保存到文件
|
||||
pub async fn generate_thumbnail_from_data(
|
||||
&self,
|
||||
image_data: &[u8],
|
||||
thumbnail_filename: &str,
|
||||
) -> Result<(), ImageProcessorError> {
|
||||
// 使用统一的缩略图生成方法
|
||||
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(())
|
||||
}
|
||||
/// 检测图片格式
|
||||
fn detect_image_format(&self, image_data: &[u8]) -> Option<String> {
|
||||
if image_data.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
|
||||
/// 从内存中的图片数据生成缩略图数据(不保存到文件)
|
||||
pub async fn generate_thumbnail_from_memory(
|
||||
&self,
|
||||
image_data: &[u8],
|
||||
_thumbnail_filename: &str,
|
||||
) -> Result<Vec<u8>, ImageProcessorError> {
|
||||
// 加载图片
|
||||
let img = image::load_from_memory(image_data)?;
|
||||
|
||||
// 生成缩略图(600x600,保持宽高比)
|
||||
let thumbnail = img.thumbnail(600, 600);
|
||||
|
||||
// 将缩略图数据保存到内存缓冲区
|
||||
let mut buffer = std::io::Cursor::new(Vec::new());
|
||||
thumbnail.write_to(&mut buffer, ImageFormat::Jpeg)?;
|
||||
|
||||
Ok(buffer.into_inner())
|
||||
match &image_data[0..12] {
|
||||
b"\xff\xd8\xff" => Some("JPEG".to_string()),
|
||||
b"\x89PNG\r\n\x1a\n" => Some("PNG".to_string()),
|
||||
b"GIF87a" => Some("GIF87a".to_string()),
|
||||
b"GIF89a" => Some("GIF89a".to_string()),
|
||||
b"BM" => Some("BMP".to_string()),
|
||||
b"RIFF" if image_data.len() > 12 && &image_data[8..12] == b"WEBP" => {
|
||||
Some("WebP".to_string())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,4 +186,4 @@ pub struct ImageInfo {
|
||||
pub height: i32,
|
||||
pub file_size: i64,
|
||||
pub mime_type: String,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user