1

Here's a minimal code sample that should convert rgb to rgba image (goal: make white background transparent):

extern crate image;

fn main() {
    // ```open``` returns a `DynamicImage` on success.
    let img = image::open("image_with_white_background.png").unwrap();

    // Should make white background transparent
    // Found a similar question: https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent
    // Is there a nice method for that loop (see the answer to the question above)?
    let img = img.to_rgba();

    img.save("image_with_transparent_background.png").unwrap();
}

It don't really work though, there's still white background in image_with_transparent_background.png.

Here's the image I work with:

picture

Update: this piece of code works, but I wonder if there's something more elegant (e.g., can I reuse existing library call instead):

fn main() {
    let img = image::open("image_with_white_background.png").unwrap();


    let mut img = img.to_rgba();
    for p in img.pixels_mut() {
        if p[0] == 255 && p[1] == 255 && p[2] == 255 {
            p[3] = 0;
        }
    }

    img.save("image_with_transparent_background.png").unwrap();
}
H. Desane
  • 593
  • 1
  • 8
  • 16
  • What do you mean "does not work". A proper description would be good. Is an error emitted? Does the result does not look like what you want? How does it differ? – hellow Feb 13 '19 at 12:33
  • @hellow the result still have a white background which is not I want. – H. Desane Feb 13 '19 at 12:34
  • 2
    Out of curiosity. Why would you expect it to be transparent now? The color white is still white. You haven't changed anything. You have to modify white to transparent somehow – hellow Feb 13 '19 at 12:35
  • @hellow I think that's exactly what I want actually. – H. Desane Feb 13 '19 at 12:37
  • Imo, you need to take a look at this [topic](https://www.reddit.com/r/rust/comments/3mhf0y/piston_question_how_can_i_change_the_color_of_an/) Since you did not change the color itself, even though you change rgb to rgba, it does not work as you wanted. – Akiner Alkan Feb 13 '19 at 12:41
  • @AkinerAlkan tbh I'm still confused a bit, I thought it should be pretty simple (e.g., worst case is to iterate over all pixels, if pixel = (255, 255, 255) then set it's transparency to 0 (all others have 1). I thought there's a special method for this loop operation. E.g. look at this question: https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent – H. Desane Feb 13 '19 at 12:48
  • @H.Desane In your reference question, After conversion to the rgba, there is a loop that makes the conversion process. So as similar you need to add this implementation to your code as well I guess. – Akiner Alkan Feb 13 '19 at 12:54
  • 2
    A little bit off-topic, but this kind of image would gain to be in svg. – Boiethios Feb 13 '19 at 13:20

0 Answers0