Rust图像处理:resize和crop
Rust是一种现代系统编程语言,越来越多地应用于需要高性能和高可靠性的任务。图像处理也不例外。在本文中,我们将探讨两个关键操作——调整大小(resize)和裁剪(crop)——使用Rust生态系统。主要库:image(加载、保存、基本操作)和imageproc(高级处理)。
为什么选择Rust进行图像处理?
Rust提供:
- 安全的内存管理——无内存泄漏和数据竞争。
- 极致性能——与C/C++相当。
- 丰富的生态系统——
imagecrate支持JPEG、PNG、GIF、BMP、WEBP等格式。 - 并发性——易于在多核处理器上扩展处理能力。
安装依赖
在Cargo.toml中添加:
[dependencies]image = "0.25"imageproc = "0.25" # 用于高级滤镜(可选)请查看crates.io获取最新版本。
加载和保存图像
从一个基本示例开始——打开文件并保存其副本:
use image::{GenericImageView, ImageFormat};
fn main() -> Result<(), Box<dyn std::error::Error>> { // 加载图像 let img = image::open("input.jpg")?; // 输出尺寸 println!("宽度: {}, 高度: {}", img.width(), img.height()); // 保存为其他格式 img.save("output.png")?; Ok(())}image::open方法会根据文件扩展名或内容自动检测格式。
调整大小(resize)
resize函数接受新的宽度和高度,以及插值滤波器。可用的滤波器包括:Nearest、Triangle、CatmullRom、Gaussian、Lanczos3等。
use image::{imageops::FilterType, GenericImageView};
fn resize_image(path: &str, new_width: u32, new_height: u32) -> Result<(), Box<dyn std::error::Error>> { let img = image::open(path)?; // 使用Lanczos3滤波器调整大小(高质量) let resized = img.resize(new_width, new_height, FilterType::Lanczos3); // 保存结果 resized.save("resized.jpg")?; println!("尺寸已更改: {}x{} → {}x{}", img.width(), img.height(), new_width, new_height); Ok(())}提示: 对于快速处理,使用FilterType::Nearest(无插值);对于最高质量,使用Lanczos3。
按比例调整大小
要保留宽高比,请使用resize_to_fill(填充区域)或resize_to_fit(适应矩形):
use image::imageops::FilterType;
fn resize_proportional(path: &str, max_width: u32, max_height: u32) -> Result<(), Box<dyn std::error::Error>> { let img = image::open(path)?; // 适应矩形(保持比例) let fitted = img.resize_to_fit(max_width, max_height, FilterType::Triangle); fitted.save("fitted.jpg")?; // 填充区域(会裁剪多余部分) let filled = img.resize_to_fill(max_width, max_height, FilterType::Triangle); filled.save("filled.jpg")?; Ok(())}裁剪图像(crop)
裁剪通过crop方法执行,该方法接受左上角坐标(x, y)和区域尺寸:
use image::Gener