源码
use super::image::Image;pub trait PixelFetch {fn get_pixel(bitmap: &Image, x: i32, y: i32) -> u32;
}pub struct PadFetch;
impl PixelFetch for PadFetch{fn get_pixel(bitmap: &Image, mut x: i32, mut y: i32) -> u32 {if x < 0 {x = 0;}if x >= bitmap.width {x = bitmap.width - 1;}if y < 0 {y = 0;}if y >= bitmap.height {y = bitmap.height - 1;}bitmap.data[(y * bitmap.width + x) as usize]}
}
代码分析
这段代码定义了一个像素获取的 trait 和其实现,主要用于从图像中安全地获取像素值,同时处理越界访问的情况。以下是详细解释:
- 引入依赖和定义 trait
use super::image::Image;pub trait PixelFetch {fn get_pixel(bitmap: &Image, x: i32, y: i32) -> u32;
}
-
use super::image::Image;: 引入父模块中的 Image 类型,表示图像数据结构。
-
PixelFetch trait: 定义了一个接口,要求实现 get_pixel 方法,用于从图像中获取指定坐标 (x, y) 的像素值(u32 类型)。
- 实现 PadFetch 结构体
pub struct PadFetch;
impl PixelFetch for PadFetch {fn get_pixel(bitmap: &Image, mut x: i32, mut y: i32) -> u32 {// 处理 x 越界if x < 0 {x = 0;}if x >= bitmap.width {x = bitmap.width - 1;}// 处理 y 越界if y < 0 {y = 0;}if y >= bitmap.height {y = bitmap.height - 1;}// 返回安全坐标下的像素值bitmap.data[(y * bitmap.width + x) as usize]}
}
-
PadFetch: 一个空结构体,实现了 PixelFetch trait,提供边界填充(Padding)的像素获取策略。
-
越界处理逻辑:
-
如果 x 或 y 为负数,将其修正为 0(图像左/上边界)。
-
如果 x 或 y 超过图像宽度或高度,将其修正为 width - 1 或 height - 1(图像右/下边界)。
-
-
像素计算: 修正后的坐标通过 y * width + x 转换为线性索引,从 bitmap.data(像素数组)中取出对应的 u32 像素值。
关键点总结
-
用途: 安全地获取图像像素,避免因越界访问导致 panic 或内存不安全。
-
策略: 越界时返回最近的边界像素值(类似“边缘填充”效果)。
-
适用场景: 图像处理中需要处理边界条件的操作(如卷积滤波、缩放等)。
如果需要其他边界处理方式(如镜像、重复等),可以定义新的结构体并实现 PixelFetch trait。