Determine The Bit Depth of a DynamicImage in Rust

Viewed 155

How could one determine the bit depth of a image::DynamicImage in rust? I'm using fltk-rs function for creating an RgbImageand RgbImage::new() requires that I specify the bit depth of the Rgb byte data its going to be created from. The images I'm loading in my program have various bit depths, so I need to be able to determine the bit depth value for image dynamically.

impl RgbImage

pub fn new(
    data: &[u8],
    w: u32,
    h: u32,
    depth: u32
) -> Result<RgbImage, FltkError>

Here's a typical use case where I would like to know the bit depth of my DynamicImage:

image = "0.23.12"
fltk = "0.12.0"
use image::*;
use fltk::*;
//...
let img = image::open("my_img.png").unwrap(); //<---find the bit depth of this loaded image
let (imgx, imgy) = img.dimensions();
let fltk_rgb = RgbImage::new(&img.to_bytes(), imgx, imgy, 4).unwrap(); //<---then use bit depth value here
//...
2 Answers

As @Ivan C said, the easiest way is with a look-up table in a match statement.

use image::DynamicImage;

pub fn bit_depth(image: &image::DynamicImage) -> u32 {
    use DynamicImage::*;

    match image {
        ImageLuma8(_) => 1,
        ImageLumaA8(_) => 2,
        ImageRgb8(_) => 3,
        ImageRgba8(_) => 4,
        ImageBgr8(_) => 3,
        ImageBgra8(_) => 4,
        ImageLuma16(_) => 2,
        ImageLumaA16(_) => 4,
        ImageRgb16(_) => 6,
        ImageRgba16(_) => 8,
    }
}

Rust Playground

That said, you'll have to be a little bit careful. FLTK makes some assumptions about what the bit depth says about color order in each pixel (documented here, note in particular that it assumes RGB color order and will reject any bit depths >4). It might be better to create a function that takes a DynamicImage and converts it if necessary to the appropriate FLTK-compatible representation in the image crate (essentially one of ImageLuma8, ImageLumaA8, ImageRgb8 or ImageRgba8), then hard-codes the bit depth for the resulting image type.

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

img.color().bytes_per_pixel()
Related