Failing to handle existing and non-existing image


#1

I am trying to draw on an image that may exist or may have to be created. In outline:

fn draw(name: &str) -> Result<()> {
    let mut img;
    if Path::new(name).exists() {
        img = image::open(name)?;
    } else {
        img = blank_image();
    }
   draw_details(&mut img)?;
}

fn blank_image() -> DynamicImage {
    let bg = Rgba([200u8, 200u8, 200u8, 255u8]);
    let mut img = ImageBuffer::new(200, 300);
    draw_filled_rect_mut(&mut img, Rect::at(0, 0).of_size(200, 300), bg);
    img
}

This doesn’t work because blank_image returns an ImageBuffer not a DynamicImage. But is there any way I could return a DynamicImage, so that in both cases the original img in draw can be used?


#2

It appears you can create a DynamicImage by wrapping the image buffer in one variant:

fn blank_image() -> DynamicImage {
    ....
    DynamicImage::ImageRgba8(img)
}

#3

Thanks! Actually, what I did in the end was instead of creating an ImageBuffer I created an RgbaImage and used that as the parameter type & it seemed to work fine. Oh, but now I find that either works.

Ok, now I find that: creating an ImageBuffer or RgbaImage in one function means that I must pass either as an RgbaImage to another function. But if I create an image using image::open(), I can pass it as a DynamicImage. Which I find a bit confusing, but it works:-)