Determine if loaded image has alpha channel using Rust image crate

Viewed 328

For the purposes of drawing images into a GUI, I need to determine if an image has an alpha channel. I've asked a similar question in regards to getting the bit depth of an image::DynamicImage, but was wondering if the image crate has any other means of detecting an alpha channel for a DynamicImage other than using such a match statement.

image = "0.23.14"
use image::*;
use image::io::Reader as ImageReader;

fn main(){
    let loaded_img: DynamicImage = ImageReader::open(path).unwrap().decode().unwrap();  
    dbg!(is_rgba(loaded_img));
}

fn has_alpha(img: DynamicImage) -> bool{
    match img {
        DynamicImage::ImageLumaA8(_) => true,
        DynamicImage::ImageRgba8(_) => true,
        DynamicImage::ImageBgra8(_) => true,
        DynamicImage::ImageLumaA16(_) => true,
        DynamicImage::ImageRgba16(_) => true,
        _=>false
    }
}
1 Answers

DynamicImage has a color() method to get the color type, which itself has a has_alpha() method:

fn has_alpha(img: DynamicImage) -> bool {
    img.color().has_alpha()
}
Related