From 4115c041076b47543e564f10670c2456e35f4873 Mon Sep 17 00:00:00 2001 From: lychang <632945494@qq.com> Date: Mon, 23 Mar 2026 02:38:17 +0800 Subject: [PATCH] update code level --- .env | 1 - assets/css/style.css | 82 +++++++++++++++ assets/js/album.js | 15 ++- assets/js/app.js | 207 ++++++++++++++++++++++++++++++++++--- src/database.rs | 65 +++++++++++- src/image_processor.rs | 64 +++++++++--- src/import.rs | 228 ++++++++++++++++++++++++++++++++++++++++- src/routes.rs | 95 +++++++---------- 8 files changed, 662 insertions(+), 95 deletions(-) delete mode 100644 .env diff --git a/.env b/.env deleted file mode 100644 index 1851c03..0000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=sqlite:data/imager.db \ No newline at end of file diff --git a/assets/css/style.css b/assets/css/style.css index 4ac332c..d877e4c 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -1468,6 +1468,88 @@ body { } } +/* 分页加载样式 */ +.loading-more { + text-align: center; + padding: 40px 20px; + background: var(--white); + border-radius: var(--border-radius); + box-shadow: var(--shadow-sm); + margin: 20px 0; + border: 1px solid var(--medium-gray); +} + +.loading-spinner { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + color: var(--text-light); + font-size: 1rem; +} + +.loading-spinner .fa-spinner { + color: var(--secondary-blue); + font-size: 1.2rem; +} + +.load-more-error { + text-align: center; + padding: 30px 20px; + background: #fef2f2; + border-radius: var(--border-radius); + box-shadow: var(--shadow-sm); + margin: 20px 0; + border: 1px solid #fecaca; + color: #dc2626; +} + +.error-content { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + font-size: 1rem; +} + +.error-content .fa-exclamation-triangle { + font-size: 1.2rem; +} + +.error-content a { + color: var(--primary-blue); + text-decoration: underline; + cursor: pointer; +} + +.error-content a:hover { + color: var(--secondary-blue); +} + +/* 移动端分页样式优化 */ +@media (max-width: 768px) { + .loading-more { + padding: 30px 15px; + margin: 15px 0; + } + + .loading-spinner { + font-size: 0.9rem; + gap: 10px; + } + + .load-more-error { + padding: 25px 15px; + margin: 15px 0; + } + + .error-content { + font-size: 0.9rem; + flex-direction: column; + gap: 8px; + } +} + /* 打印样式 */ @media print { .search-container, diff --git a/assets/js/album.js b/assets/js/album.js index 8b3ab03..2732a85 100644 --- a/assets/js/album.js +++ b/assets/js/album.js @@ -128,8 +128,7 @@ function displayImages() { const title = image.title || `图片 ${index + 1}`; // 检查图片是否已被收藏 - const isFavorited = isImageFavorited(image.id || image.original_url); - + isImageFavorited(image.id || image.original_url); return `
= scrollHeight - 200) { + loadMoreAlbums(); + } +} + +// 加载更多相册 +async function loadMoreAlbums() { + if (isLoadingMore || !hasMoreAlbums) return; + + isLoadingMore = true; + try { + await loadAlbums(); + } catch (error) { + console.error('加载更多相册失败:', error); + showLoadMoreError(); + } finally { + isLoadingMore = false; + } +} + +// 显示加载更多错误 +function showLoadMoreError() { + const container = document.getElementById('albums-container'); + const errorElement = document.createElement('div'); + errorElement.className = 'load-more-error'; + errorElement.innerHTML = ` +
+ + 加载失败,点击重试 +
+ `; + + const existingError = container.querySelector('.load-more-error'); + if (existingError) { + existingError.remove(); + } + + container.appendChild(errorElement); +} + // 防抖搜索 function debouncedSearch() { searchAlbums(); @@ -67,25 +132,129 @@ function showSkeleton(count = 6) { `).join(''); } -// 加载所有相册 -async function loadAlbums() { - try { - // 显示骨架屏 - showSkeleton(); +// 显示加载更多指示器 +function showLoadingMore() { + const container = document.getElementById('albums-container'); + const loadingIndicator = document.createElement('div'); + loadingIndicator.id = 'loading-more'; + loadingIndicator.className = 'loading-more'; + loadingIndicator.innerHTML = ` +
+ + 加载更多相册... +
+ `; + container.appendChild(loadingIndicator); +} - const response = await fetch(`${API_BASE}/albums`); +// 隐藏加载更多指示器 +function hideLoadingMore() { + const loadingIndicator = document.getElementById('loading-more'); + if (loadingIndicator) { + loadingIndicator.remove(); + } +} + +// 追加相册到列表 +function appendAlbums(albums) { + const container = document.getElementById('albums-container'); + const newAlbumsHTML = albums.map(album => { + // 处理封面图片URL - 使用懒加载 + let coverImageUrl = '/assets/placeholder.svg'; + let dataSrc = ''; + + if (album.cover_image_id) { + dataSrc = `/api/thumbnail/${album.cover_image_id}`; + coverImageUrl = '/assets/placeholder.svg'; // 初始使用占位图 + } + + // 格式化日期 + const createdDate = new Date(album.created_at).toLocaleDateString('zh-CN'); + + return ` +
+
+ ${album.title} +
+
+

${album.title}

+
+ ${album.image_count} 张图片 + ${createdDate} +
+ + 查看相册 + +
+
+ `; + }).join(''); + + // 移除加载指示器并添加新相册 + hideLoadingMore(); + container.insertAdjacentHTML('beforeend', newAlbumsHTML); +} + +// 加载所有相册 +async function loadAlbums(reset = false) { + try { + if (reset) { + currentPage = 1; + allAlbums = []; + hasMoreAlbums = true; + const container = document.getElementById('albums-container'); + container.innerHTML = ''; + } + + if (!hasMoreAlbums) return; + + // 显示骨架屏 + if (currentPage === 1) { + showSkeleton(); + } else { + showLoadingMore(); + } + + const response = await fetch(`${API_BASE}/albums?page=${currentPage}&limit=${albumsPerPage}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } - allAlbums = await response.json(); - displayAlbums(allAlbums); + + const newAlbums = await response.json(); + + // 检查是否还有更多数据 + if (newAlbums.length < albumsPerPage) { + hasMoreAlbums = false; + } + + // 合并到现有相册列表 + allAlbums = [...allAlbums, ...newAlbums]; + + if (currentPage === 1) { + displayAlbums(allAlbums); + } else { + appendAlbums(newAlbums); + } + updateStats(allAlbums); // 初始化图片懒加载 initLazyLoading(); + + currentPage++; + + // 隐藏加载更多指示器 + hideLoadingMore(); } catch (error) { console.error('加载相册失败:', error); showError('加载相册数据失败,请刷新页面重试'); + hideLoadingMore(); } } @@ -94,21 +263,33 @@ async function searchAlbums() { const searchTerm = document.getElementById('search-input').value.toLowerCase().trim(); if (searchTerm === '') { - // 显示所有相册 - displayAlbums(allAlbums); - updateStats(allAlbums); + // 显示所有相册,重置分页 + loadAlbums(true); return; } try { + // 重置搜索状态 + currentPage = 1; + allAlbums = []; + hasMoreAlbums = true; + // 显示搜索中的骨架屏 showSkeleton(4); - const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}`); + const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(searchTerm)}&page=${currentPage}&limit=${albumsPerPage}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } + const filteredAlbums = await response.json(); + allAlbums = filteredAlbums; + + // 检查是否还有更多数据 + if (filteredAlbums.length < albumsPerPage) { + hasMoreAlbums = false; + } + displayAlbums(filteredAlbums); if (filteredAlbums.length === 0) { @@ -119,6 +300,8 @@ async function searchAlbums() { // 初始化图片懒加载 initLazyLoading(); + + currentPage++; } catch (error) { console.error('搜索失败:', error); showError('搜索失败,请重试'); diff --git a/src/database.rs b/src/database.rs index b797f2c..95215db 100644 --- a/src/database.rs +++ b/src/database.rs @@ -6,7 +6,7 @@ use std::time::Duration; use tokio::time::sleep; pub struct Database { - pool: SqlitePool, + pub pool: SqlitePool, } impl Database { @@ -106,7 +106,11 @@ impl Database { } // 相册操作 - pub async fn get_all_albums(&self) -> Result, sqlx::Error> { + pub async fn get_all_albums(&self, page: Option, limit: Option) -> Result, sqlx::Error> { + let page = page.unwrap_or(1); + let limit = limit.unwrap_or(200); + let offset = (page - 1) * limit; + let albums = sqlx::query( r#" SELECT @@ -121,8 +125,11 @@ impl Database { LEFT JOIN images img ON img.album_id = a.id GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at ORDER BY a.document DESC + LIMIT ? OFFSET ? "# ) + .bind(limit as i64) + .bind(offset as i64) .fetch_all(&self.pool) .await?; @@ -151,8 +158,11 @@ impl Database { Ok(result) } - pub async fn search_albums(&self, query: &str) -> Result, sqlx::Error> { + pub async fn search_albums(&self, query: &str, page: Option, limit: Option) -> Result, sqlx::Error> { let search_pattern = format!("%{}%", query); + let page = page.unwrap_or(1); + let limit = limit.unwrap_or(200); + let offset = (page - 1) * limit; let albums = sqlx::query( r#" @@ -170,9 +180,12 @@ impl Database { WHERE a.title LIKE ? GROUP BY a.id, a.title, a.document, a.description, a.cover_image_id, a.created_at ORDER BY a.created_at DESC + LIMIT ? OFFSET ? "# ) .bind(&search_pattern) + .bind(limit as i64) + .bind(offset as i64) .fetch_all(&self.pool) .await?; @@ -424,6 +437,52 @@ impl Database { Ok(ids) } + /// 获取相册中的图片数量 + pub async fn get_album_image_count(&self, album_id: Uuid) -> Result { + let count = sqlx::query_scalar::<_, i64>( + "SELECT COUNT(*) FROM images WHERE album_id = ?" + ) + .bind(album_id.to_string()) + .fetch_one(&self.pool) + .await?; + + Ok(count) + } + + /// 删除相册及其关联的图片 + pub async fn delete_album(&self, album_id: Uuid) -> Result<(), sqlx::Error> { + let mut tx = self.pool.begin().await?; + + // 删除相册关联的图片 + sqlx::query("DELETE FROM images WHERE album_id = ?") + .bind(album_id.to_string()) + .execute(&mut *tx) + .await?; + + // 删除相册 + sqlx::query("DELETE FROM albums WHERE id = ?") + .bind(album_id.to_string()) + .execute(&mut *tx) + .await?; + + tx.commit().await?; + Ok(()) + } + + pub async fn update_album_cover(&self, album_id: Uuid, cover_image_id: Option) -> Result<(), sqlx::Error> { + let cover_id_str = cover_image_id.map(|id| id.to_string()); + + sqlx::query( + "UPDATE albums SET cover_image_id = ?, updated_at = datetime('now') WHERE id = ?" + ) + .bind(cover_id_str) + .bind(album_id.to_string()) + .execute(&self.pool) + .await?; + + Ok(()) + } + pub async fn get_image(&self, image_id: Uuid) -> Result, sqlx::Error> { let row = sqlx::query( "SELECT * FROM images WHERE id = ?" diff --git a/src/image_processor.rs b/src/image_processor.rs index 2f32b7d..a8d0f62 100644 --- a/src/image_processor.rs +++ b/src/image_processor.rs @@ -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> { - 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> { + // 使用统一的缩略图生成方法 + 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, Box> { + // 加载图片 + 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)] diff --git a/src/import.rs b/src/import.rs index f112b15..1aab9cc 100644 --- a/src/import.rs +++ b/src/import.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use image::GenericImageView; use serde::Deserialize; use tokio::task; +use uuid::Uuid; use crate::config::Config; use crate::database::Database; use crate::models::*; @@ -25,14 +26,59 @@ pub async fn import_existing_data(config: &Config, db: Arc) -> Result< } // 获取数据库中现有的相册列表 - let existing_albums = db.get_all_albums().await?; + let existing_albums = db.get_all_albums(None, None).await?; let existing_titles: Vec = existing_albums.iter() .map(|album| album.document.to_lowercase()) .collect(); println!("数据库中现有相册数量: {}", existing_albums.len()); - // 第一阶段:快速扫描所有相册文件夹 + // 第一阶段:检查并重新导入失败的相册 + println!("🔍 检查需要重新导入的相册..."); + let mut reimported_count = 0; + let mut deleted_count = 0; + + for album in &existing_albums { + let album_folder_path = albums_dir.join(&album.document); + + // 检查相册文件夹是否存在 + if !album_folder_path.exists() { + // 文件夹不存在,删除数据库中的相册记录 + println!("🗑️ 相册文件夹不存在,删除相册: {}", album.document); + if let Err(e) = db.delete_album(album.id).await { + eprintln!("❌ 删除相册失败: {}", e); + } else { + deleted_count += 1; + } + continue; + } + + // 检查相册是否有图片 + let image_count = db.get_album_image_count(album.id).await.unwrap_or(0); + if image_count == 0 { + // 相册存在但没有图片,尝试重新导入 + println!("🔄 重新导入相册: {} (图片数量: 0)", album.document); + match reimport_single_album(&db, &album.document, &album_folder_path, album.id).await { + Ok(count) => { + if count > 0 { + reimported_count += 1; + println!("✅ 相册 {} 重新导入成功,导入 {} 张图片", album.document, count); + } else { + println!("⚠️ 相册 {} 重新导入但没有找到图片", album.document); + } + } + Err(e) => { + eprintln!("❌ 相册 {} 重新导入失败: {}", album.document, e); + } + } + } + } + + if reimported_count > 0 || deleted_count > 0 { + println!("🎯 重新导入完成: 重新导入 {} 个相册,删除 {} 个相册", reimported_count, deleted_count); + } + + // 第二阶段:快速扫描所有相册文件夹,导入新相册 let entries: Vec<_> = fs::read_dir(albums_dir)?.collect::, _>>()?; let mut album_folders = Vec::new(); @@ -42,7 +88,6 @@ pub async fn import_existing_data(config: &Config, db: Arc) -> Result< if let Some(folder_name) = path.file_name().and_then(|s| s.to_str()) { // 检查是否已存在同名相册 if existing_titles.contains(&folder_name.to_lowercase()) { - println!("跳过已存在的相册: {}", folder_name); continue; } album_folders.push((folder_name.to_string(), path)); @@ -222,6 +267,26 @@ async fn import_single_album(db: &Database, folder_name: &str, path: &Path) -> R match db.add_images(images_to_insert).await { Ok(ids) => { println!(" 批量插入成功,共插入 {} 张图片", ids.len()); + + // 设置第一张图片为封面图片并生成缩略图 + if let Some(first_image_id) = ids.first() { + println!(" 设置第一张图片为封面图片 (ID: {})...", first_image_id); + + // 更新相册的封面图片ID + if let Err(e) = db.update_album_cover(album_id, Some(*first_image_id)).await { + eprintln!(" 更新相册封面失败: {}", e); + } + + // 获取第一张图片的信息 + if let Ok(Some(first_image)) = db.get_image(*first_image_id).await { + // 生成缩略图 + match generate_thumbnail_for_image(&first_image, path, folder_name).await { + Ok(_) => println!(" 封面缩略图生成成功"), + Err(e) => eprintln!(" 封面缩略图生成失败: {}", e), + } + } + } + Ok(ids.len()) } Err(e) => { @@ -290,4 +355,161 @@ fn get_image_info(image_path: &Path) -> Result<(i64, i32, i32), Box Result> { + println!("📁 重新导入相册: {} (ID: {})", folder_name, album_id); + + // 读取index.json文件 + let index_file_path = path.join("index.json"); + let album_title = if index_file_path.exists() { + match fs::read_to_string(&index_file_path) { + Ok(content) => { + match serde_json::from_str::(&content) { + Ok(index) => index.title, + Err(_) => folder_name.to_string(), + } + } + Err(_) => folder_name.to_string(), + } + } else { + folder_name.to_string() + }; + + println!(" 相册标题: {}", album_title); + + // 扫描图片文件 + let mut images_to_insert = Vec::new(); + let image_extensions = ["jpg", "jpeg", "png", "gif", "webp", "bmp"]; + + let entries: Vec<_> = fs::read_dir(path)?.collect::, _>>()?; + + for entry in entries { + let file_path = entry.path(); + if file_path.is_file() { + if let Some(extension) = file_path.extension().and_then(|ext| ext.to_str()) { + if image_extensions.contains(&extension.to_lowercase().as_str()) { + if let Some(filename) = file_path.file_name().and_then(|s| s.to_str()) { + // 跳过index.json文件 + if filename == "index.json" { + continue; + } + + // 获取图片信息 + let (file_size, width, height) = match get_image_info(&file_path) { + Ok(info) => info, + Err(e) => { + eprintln!(" 获取图片信息失败 {}: {}", filename, e); + continue; + } + }; + + let image = CreateImage { + album_id, + filename: format!("{}/{}", folder_name, filename), + original_url: Some(format!("/images/{}/{}", folder_name, filename)), + title: Some(filename.to_string()), + description: Some(String::new()), + file_size, + width, + height, + mime_type: match extension.to_lowercase().as_str() { + "jpg" | "jpeg" => "image/jpeg".to_string(), + "png" => "image/png".to_string(), + "gif" => "image/gif".to_string(), + "webp" => "image/webp".to_string(), + "bmp" => "image/bmp".to_string(), + _ => "application/octet-stream".to_string(), + }, + }; + + images_to_insert.push(image); + } + } + } + } + } + + println!(" 发现 {} 张图片需要导入", images_to_insert.len()); + + // 批量插入图片 + if !images_to_insert.is_empty() { + println!(" 批量插入 {} 张图片...", images_to_insert.len()); + match db.add_images(images_to_insert).await { + Ok(ids) => { + println!(" 批量插入成功,共插入 {} 张图片", ids.len()); + + // 设置第一张图片为封面图片并生成缩略图 + if let Some(first_image_id) = ids.first() { + println!(" 设置第一张图片为封面图片 (ID: {})...", first_image_id); + + // 更新相册的封面图片ID + if let Err(e) = db.update_album_cover(album_id, Some(*first_image_id)).await { + eprintln!(" 更新相册封面失败: {}", e); + } + + // 获取第一张图片的信息 + if let Ok(Some(first_image)) = db.get_image(*first_image_id).await { + // 生成缩略图 + match generate_thumbnail_for_image(&first_image, path, folder_name).await { + Ok(_) => println!(" 封面缩略图生成成功"), + Err(e) => eprintln!(" 封面缩略图生成失败: {}", e), + } + } + } + + Ok(ids.len()) + } + Err(e) => { + eprintln!(" 批量插入失败: {}", e); + Ok(0) + } + } + } else { + Ok(0) + } +} + +/// 为图片生成缩略图(使用ImageProcessor) +async fn generate_thumbnail_for_image( + image: &crate::models::Image, + album_path: &Path, + _folder_name: &str, +) -> Result<(), Box> { + // 构建图片文件路径 + let image_filename = image.filename.split('/').last().unwrap_or(&image.filename); + let image_path = album_path.join(image_filename); + + if !image_path.exists() { + return Err(format!("图片文件不存在: {}", image_path.display()).into()); + } + + // 读取图片数据 + let image_data = fs::read(&image_path)?; + + // 创建临时的ImageProcessor实例 + // 注意:这里使用默认的缩略图目录路径 + let config = crate::config::StorageConfig { + images_dir: Path::new("./albums").to_path_buf(), + thumbnails_dir: Path::new("./thumbnails").to_path_buf(), + }; + + let image_processor = crate::image_processor::ImageProcessor::new(config); + + // 生成缩略图 + match image_processor.generate_thumbnail_from_data(&image_data, &image.id.to_string()).await { + Ok(_) => { + println!(" 缩略图生成成功 (ID: {})", image.id); + Ok(()) + } + Err(e) => { + Err(format!("缩略图生成失败: {}", e).into()) + } + } } \ No newline at end of file diff --git a/src/routes.rs b/src/routes.rs index 378d956..5a2bfe8 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -6,8 +6,14 @@ use std::fs; use std::sync::Arc; use uuid::Uuid; -pub async fn get_albums(db: web::Data>) -> impl Responder { - match db.get_all_albums().await { +pub async fn get_albums( + db: web::Data>, + query: web::Query>, +) -> impl Responder { + let page = query.get("page").and_then(|s| s.parse::().ok()); + let limit = query.get("limit").and_then(|s| s.parse::().ok()); + + match db.get_all_albums(page, limit).await { Ok(albums) => HttpResponse::Ok().json(albums), Err(e) => { eprintln!("获取相册列表失败: {}", e); @@ -196,9 +202,11 @@ pub async fn search_albums( query: web::Query>, ) -> impl Responder { let q = query.get("q").map(|s| s.as_str()).unwrap_or(""); + let page = query.get("page").and_then(|s| s.parse::().ok()); + let limit = query.get("limit").and_then(|s| s.parse::().ok()); if q.is_empty() { - return match db.get_all_albums().await { + return match db.get_all_albums(page, limit).await { Ok(albums) => HttpResponse::Ok().json(albums), Err(e) => { eprintln!("获取相册列表失败: {}", e); @@ -209,7 +217,7 @@ pub async fn search_albums( }; } - match db.search_albums(q).await { + match db.search_albums(q, page, limit).await { Ok(albums) => HttpResponse::Ok().json(albums), Err(e) => { eprintln!("搜索相册失败: {}", e); @@ -306,64 +314,33 @@ pub async fn get_thumbnail( // 生成缩略图并返回 match fs::read(&original_path) { Ok(data) => { - match image::load_from_memory(&data) { - Ok(img) => { - // 在内存中生成缩略图,避免重复文件读写 - let thumbnail = img.thumbnail(800, 600); - - // 使用临时文件来生成缩略图数据 - let temp_dir = std::env::temp_dir(); - let temp_file = - temp_dir.join(format!("temp_thumb_{}", Uuid::new_v4())); - - if let Err(e) = - thumbnail.save_with_format(&temp_file, image::ImageFormat::Jpeg) - { - eprintln!("生成缩略图失败: {}", e); - // 如果生成缩略图失败,返回原始图片 - return HttpResponse::Ok() - .content_type(image.mime_type) - .body(data); - } - - // 读取缩略图数据 - match fs::read(&temp_file) { - Ok(thumbnail_data) => { - // 异步保存缩略图到文件(不阻塞响应) - let config_clone = image_processor.config.clone(); - let filename_clone = image.id.clone(); - let thumbnail_data_clone = thumbnail_data.clone(); - tokio::spawn(async move { - let thumbnail_path = config_clone - .thumbnails_dir - .join(filename_clone.to_string()); - if let Err(e) = - fs::write(&thumbnail_path, &thumbnail_data_clone) - { - eprintln!("保存缩略图文件失败: {}", e); - } - }); - - // 清理临时文件 - let _ = fs::remove_file(&temp_file); - - // 返回缩略图数据 - HttpResponse::Ok() - .content_type("image/jpeg") - .body(thumbnail_data) + // 使用ImageProcessor生成缩略图 + match image_processor.generate_thumbnail_from_memory(&data, &image.id.to_string()).await { + Ok(thumbnail_data) => { + // 异步保存缩略图到文件(不阻塞响应) + let config_clone = image_processor.config.clone(); + let filename_clone = image.id.clone(); + let thumbnail_data_clone = thumbnail_data.clone(); + tokio::spawn(async move { + let thumbnail_path = config_clone + .thumbnails_dir + .join(filename_clone.to_string()); + if let Err(e) = + fs::write(&thumbnail_path, &thumbnail_data_clone) + { + eprintln!("保存缩略图文件失败: {}", e); } - Err(e) => { - eprintln!("读取缩略图数据失败: {}", e); - // 如果读取失败,返回原始图片 - HttpResponse::Ok().content_type(image.mime_type).body(data) - } - } + }); + + // 返回缩略图数据 + HttpResponse::Ok() + .content_type("image/jpeg") + .body(thumbnail_data) } Err(e) => { - eprintln!("加载图片失败: {}", e); - HttpResponse::InternalServerError().json(serde_json::json!({ - "error": "加载图片失败" - })) + eprintln!("生成缩略图失败: {}", e); + // 如果生成缩略图失败,返回原始图片 + HttpResponse::Ok().content_type(image.mime_type).body(data) } } }