Skip to content

Commit c9889d0

Browse files
committed
feat(core): 新增 WebP 图像压缩功能
在 `Cargo.toml` 和 `crates/core/Cargo.toml` 中添加了对 `webp` 库的依赖,以支持 WebP 图像格式的压缩。 在 `crates/core/src/image.rs` 中修改了图像压缩和缩略图生成的逻辑,使用 `webp::Encoder` 进行 WebP 格式的图像压缩。更新了注释以明确说明压缩为有损 WebP 格式。
1 parent 81772e7 commit c9889d0

File tree

4 files changed

+42
-10
lines changed

4 files changed

+42
-10
lines changed

Cargo.lock

Lines changed: 33 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ bytes = "1"
4444

4545
# Image processing
4646
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "gif", "webp"] }
47+
webp = "0.3"
4748

4849
# HTTP client
4950
reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false }

crates/core/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,6 @@ dashmap.workspace = true
2121
rand.workspace = true
2222
tokio = { workspace = true }
2323
image.workspace = true
24+
webp.workspace = true
2425
reqwest.workspace = true
2526
regex.workspace = true

crates/core/src/image.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -116,22 +116,19 @@ impl ImageService {
116116
let width = img.width() as i32;
117117
let height = img.height() as i32;
118118

119-
// 6. Compress to WebP
119+
// 6. Compress to WebP (lossy)
120120
let webp_data = {
121-
let mut buf = Cursor::new(Vec::new());
122-
img.write_to(&mut buf, image::ImageFormat::WebP)
123-
.map_err(|e| AppError::Internal(format!("WebP 编码失败: {e}")))?;
124-
buf.into_inner()
121+
let encoder = webp::Encoder::from_image(&img)
122+
.map_err(|e| AppError::Internal(format!("WebP 编码器创建失败: {e}")))?;
123+
encoder.encode(config.compression_quality as f32).to_vec()
125124
};
126125

127126
// 7. Generate 300x300 thumbnail
128127
let thumb_data = {
129128
let thumb = img.thumbnail(300, 300);
130-
let mut buf = Cursor::new(Vec::new());
131-
thumb
132-
.write_to(&mut buf, image::ImageFormat::WebP)
133-
.map_err(|e| AppError::Internal(format!("缩略图生成失败: {e}")))?;
134-
buf.into_inner()
129+
let encoder = webp::Encoder::from_image(&thumb)
130+
.map_err(|e| AppError::Internal(format!("缩略图编码器创建失败: {e}")))?;
131+
encoder.encode(config.compression_quality as f32).to_vec()
135132
};
136133

137134
let size = webp_data.len() as i64;

0 commit comments

Comments
 (0)