Image put_pixel problem

Having a problem getting this to update the pixels:

pub fn apply_alpha_threshold(img: &mut image::DynamicImage, threshold: u8) {
    const CLEARPIXEL: image::Rgba::<u8> = image::Rgba::<u8>([0,0,0,0]); // transparent pixel
    let (width, height) = img.dimensions();
    for x in 0..width {
        for y in 0..height {
            let pixel = img.get_pixel(x,y);
            if pixel.to_rgba()[3] < threshold {                    // if below threshold
                img.put_pixel(x,y,CLEARPIXEL);          // set to clear

which is called by:

let mut image = image::io::Reader::open(texturefile(uuid,&"png"))?.decode()?; 
image::imageops::flip_vertical_in_place(&mut image);  
apply_alpha_threshold(&mut image, 128);                     
let rgba = image.to_rgba8();
// Onward to display.

This runs, but does not affect the image.
Do I need to do something to flush the working buffer back to the image structure, as in Python's image library?

I tried using get_pixel_mut, as documented here. But that's unimplemented now, and panics. See line 1906 of

Have you checked whether the if condition is ever evaluating to true?

It looks like DynImage::get_pixel_mut is deprecated, but ImageBuffer::get_pixel_mut is not.

Since you are already converting to RgbaImage, you should do your pixel access after the conversion (so you don't need to convert each pixel to and from RGBA individually, and then convert all of them again). Then you can use get_pixel_mut, or even better, pixels_mut:

pub fn apply_alpha_threshold(img: &mut image::RgbaImage, threshold: u8) {
    const CLEARPIXEL: image::Rgba<u8> = image::Rgba([0,0,0,0]);
    for pixel in img.pixels_mut() {
        if pixel[3] < threshold {
            *pixel = CLEARPIXEL;

let mut rgba = image.to_rgba8();
apply_alpha_threshold(&mut rgba, 128);                     

Yes, but not often enough. Need to check if certain images came through with an alpha.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.