为了学习生锈,我尝试实现一个通用的图像类/对象。
我对Image :: save(...)函数和RgbaGeneric的Pixel :: gray()的实现有问题。
编译器说我必须使用From或Into特性。但是我不知道语法看起来如何。所有使它起作用的尝试都失败了。
mod image {
use std::fmt;
use std::path::Path;
use std::io::Write;
use std::fs::File;
#[derive(Clone, Debug)]
pub struct RgbaGeneric<T> {
r: T, g: T, b: T, a: T,
}
trait Pixel<T> {
fn red(&self) -> T;
fn green(&self) -> T;
fn blue(&self) -> T;
fn alpha(&self) -> T;
fn gray(&self) -> T;
}
impl<T> Pixel<T> for RgbaGeneric<T> {
fn red(&self) -> T { return self.r;}
fn green(&self) -> T { return self.g; }
fn blue(&self) -> T { return self.b; }
fn alpha(&self) -> T { return self.a; }
fn gray(&self) -> T {
return (self.r as f32 * 0.21 +
self.g as f32 * 0.72 +
self.b as f32 * 0.07) as T;
}
}
impl<T> RgbaGeneric<T> {
pub fn new(r: T, g: T, b: T, a: T) -> RgbaGeneric<T> {
RgbaGeneric { r, g, b, a }
}
}
pub type RgbaU8 = RgbaGeneric<u8>;
pub struct Image<T> {
width: usize, height: usize, data: Vec<T>,
}
pub type ImageRgbaU8 = Image<RgbaU8>;
impl<T> Image<T>
where
T: Clone + Pixel<T>
{
pub fn new(width: usize, height: usize, val: T) -> Image<T> {
Image {
width,
height,
data: vec![val; width * height],
}
}
pub fn width(&self) -> usize { return self.width; }
pub fn height(&self) -> usize { return self.height; }
pub fn pixel_count(&self) -> usize {
return self.width * self.height;
}
pub fn pixels(&self) -> &[T] { return self.data.as_slice(); }
pub fn pixel(&self, x: usize, y: usize) -> &T {
return &self.data[self.index(x, y)];
}
pub fn set_pixel(&mut self, x: usize, y: usize, pixel: T) {
let idx = self.index(x, y);
self.data[idx] = pixel;
}
pub fn save(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = try!(File::create(&path));
let header = format!("P6 {} {} 255\n", self.width, self.height);
try!(file.write(header.as_bytes()));
for y in 0..self.height() {
for x in 0..self.width() {
let pix = self.pixel(x,y);
try!(file.write(pix.red()));
try!(file.write(pix.green()));
try!(file.write(pix.blue()));
}
}
return Ok(());
}
fn index(&self, x: usize, y: usize) -> usize {
return y * &self.width + x;
}
}
}
答案 0 :(得分:0)
gray
方法的实现应如下所示:
impl<T> Pixel<T> for RgbaGeneric<T> where
f32: std::convert::From<T>,
T: std::convert::From<f32>{
fn red(&self) -> T { return self.r;}
fn green(&self) -> T { return self.g; }
fn blue(&self) -> T { return self.b; }
fn alpha(&self) -> T { return self.a; }
fn gray(&self) -> T {
return (Into::<f32>::into(self.r) * 0.21 +
Into::<f32>::into(self.g) * 0.72 +
Into::<f32>::into(self.b) * 0.07).into();
}
}
在该块的标题中,我们说我们的T
可以与f32
类型进行转换,然后我们使用into()
方法,因为as
表达式只能使用可以在原始类型之间进行转换(编译器暗示T
可以是任何类型)。