【学Rust写CAD】26 图形像素获取(pixel_fetch.rs)

源码

rust 复制代码
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 和其实现,主要用于从图像中安全地获取像素值,同时处理越界访问的情况。以下是详细解释:

  1. 引入依赖和定义 trait
rust 复制代码
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 类型)。

  1. 实现 PadFetch 结构体
rust 复制代码
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。

相关推荐
superman超哥1 天前
Serde 性能优化的终极武器
开发语言·rust·编程语言·rust serde·serde性能优化·rust开发工具
sayang_shao2 天前
Rust多线程编程学习笔记
笔记·学习·rust
鸿乃江边鸟2 天前
Spark Datafusion Comet 向量化Rust Native--读数据
rust·spark·native·arrow
硬汉嵌入式2 天前
基于Rust构建的单片机Ariel RTOS,支持Cortex-M、RISC-V 和 Xtensa
单片机·rust·risc-v
低调滴开发3 天前
Tauri开发桌面端服务,配置指定防火墙端口
rust·tauri·桌面端·windows防火墙规则
咚为3 天前
Rust Cell使用与原理
开发语言·网络·rust
咸甜适中3 天前
rust的docx-rs库,自定义docx模版批量生成docx文档(逐行注释)
开发语言·rust·docx·docx-rs
FAFU_kyp3 天前
RISC0_ZERO项目在macOs上生成链上证明避坑
开发语言·后端·学习·macos·rust
古城小栈4 天前
开发常用 宏
算法·rust
咸甜适中4 天前
rust的docx-rs库读取docx文件中的文本内容(逐行注释)
开发语言·rust·docx·docx-rs