使用image包,我可以创建一个ImageBuffer
然后放一个像素并保存它:
let mut img = ImageBuffer::new(100, 100);
img.put_pixel(50, 50);
let ref mut fout = File::create(&Path::new("test.png")).unwrap();
let _ = ImageRgb8(img).save(fout, PNG);
我想设置背景颜色(默认为黑色)。我可以迭代像素并在每个像素上放置相同颜色的像素,但我不确定它是最好的方式(看起来有点过分)。我想我错过了什么。
答案 0 :(得分:0)
如果您继续阅读文档,则会找到ImageBuffer::from_pixel
:
fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuffer<P, Vec<P::Subpixel>>
通过复制像素构建新的
ImageBuffer
答案 1 :(得分:0)
您可以使用from_pixel
和from_fn
方法构建具有自定义背景的缓冲区。
这是我的一个项目中的一个例子,我在背景上投下阴影。
enum Grace {
/// How much "grace" time have passed, in percents.
Good (f32),
Picked,
Delayed,
Closed,
/// Closed by GM without player making a choice.
Miss}
impl Grace {
fn from_time (opened: i64, now: i64) -> Grace {
let delta = now - (opened + 7200); // First two hours are "free".
if delta <= 0 {return Grace::Good (0.0)}
let percent = (delta * 100) as f32 / time::Duration::hours (24) .num_seconds() as f32;
if percent <= 100.0 {Grace::Good (percent)} else {Grace::Delayed}}}
let mut ib = ImageBuffer::from_fn (600, 24, |x, y| Rgba (match grace {
Grace::Picked | Grace::Closed => [200, 200, 255, (255 * y / 24) as u8],
Grace::Good (pc) => [pc as u8, (70 + (130 * x / 600)) as u8, 0, (255 * y / 24) as u8],
Grace::Delayed => [(70 + (130 * x / 600)) as u8, (70 + (130 * x / 600)) as u8, 0, (255 * y / 24) as u8],
Grace::Miss => [(70 + (130 * x / 600)) as u8, 0, 0, (255 * y / 24) as u8]}));