细节调整及优化(26.8.3)
This commit is contained in:
@@ -295,3 +295,29 @@ pub fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
.ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// 生成缩略图 PNG(最长边不超过 max_dim 像素)。
|
||||
/// 小图直接复用 `dib_to_png` 结果;大图降采样后重新编码,供弹窗悬停预览使用。
|
||||
pub fn dib_to_thumbnail(dib: &[u8], max_dim: u32) -> Option<Vec<u8>> {
|
||||
use image::codecs::png::PngEncoder;
|
||||
use image::GenericImageView;
|
||||
use image::ImageEncoder;
|
||||
|
||||
let png = dib_to_png(dib)?;
|
||||
let img = image::load_from_memory(&png).ok()?;
|
||||
let (w, h) = img.dimensions();
|
||||
if w.max(h) <= max_dim {
|
||||
return Some(png); // 小图直接使用,避免重复编码
|
||||
}
|
||||
// 让 image 库在 max_dim×max_dim 边界内自动等比缩放,避免手算 nw/nh 与库内部
|
||||
// resize_dimensions 的取整不一致(如手算 256x10 而库实际输出 250x10),
|
||||
// 否则 write_image 的缓冲区长度断言会失败。
|
||||
let resized = img.resize(max_dim, max_dim, image::imageops::FilterType::Triangle);
|
||||
let (rw, rh) = resized.dimensions();
|
||||
let rgba = resized.to_rgba8();
|
||||
let mut buf = Vec::new();
|
||||
let enc = PngEncoder::new(&mut buf);
|
||||
enc.write_image(rgba.as_raw(), rw, rh, image::ExtendedColorType::Rgba8)
|
||||
.ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user