kornelski / imgref

A trivial Rust struct for interchange of pixel buffers with width, height & stride
https://lib.rs/crates/imgref
Apache License 2.0
59 stars 6 forks source link

How to copy pixels from one image to another? #5

Closed RazrFalcon closed 6 years ago

RazrFalcon commented 6 years ago

Let's say I need to extract an alpha channel from an image. I've ended up with code like this:

let mut image1 = ImgVec::new(vec![RGBA8::new(0, 0, 0, 0); 4], 2, 2);
let mut image2 = ImgVec::new(vec![0; 4], 2, 2);
for (x, row) in image1.rows().enumerate() {
    for (y, p) in row.iter().enumerate() {
        image2[(x, y)] = p.a;
    }
}

It this the only way or am I missing something?

kornelski commented 6 years ago

The shortest method:

let image2 = image1.new_buf(image1.buf.iter().map(|px| px.a).collect());

or

let image2 = Img::new(image1.pixels().map(|px| px.a).collect(), image1.width(), image1.height());

Instead of buf = iter.collect(), it might be slightly faster to do:

let buf2 = Vec::with_capacity(width * height);
buf2.extend(iter);
RazrFalcon commented 6 years ago

I see. Thanks.