0

I have a BitmapImage from a StorageFile:

using (var stream = await file.OpenAsync(FileAccessMode.Read)) {
    var bitmap = new BitmapImage();
    await bitmap.SetSourceAsync(stream);
}

I've been able to check if the image is square by calculating its PixelWidth and PixelHeight properties. How do I check if image color is grayscale? This post says that Bitmap has a PixelFormat property, unfortunately, Bitmap is no longer available in UWP.

Community
  • 1
  • 1
Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97
  • In general, the only thing that is unique about a grayscale image is that it uses rather bland colors. The red, green and blue values of a pixel are roughly the same. There are some image formats that are specific to grayscale but they are very rarely used today, the hardware to display them has almost completely disappeared. Which begs the question why you care about it at all. – Hans Passant Aug 28 '16 at 14:59

2 Answers2

2

You can use BitmapDecoder to get the value of BitmapPixelFormat. Use it like this

using (var stream = await file.OpenAsync(FileAccessMode.Read)) {
    var bitmap = new BitmapImage();
    await bitmap.SetSourceAsync(stream);

    var decoder = await BitmapDecoder.CreateAsync(stream);
    BitmapPixelFormat format = decoder.BitmapPixelFormat;

    if(format == BitmapPixelFormat.Gray16 || format == BitmapPixelFormat.Gray8 )
        // Bitmap is grayscale
}
Aman Sharma
  • 698
  • 7
  • 17
  • Is it me? I can't find method `System.Windows.Media.Imaging.BitmapDecoder.CreateAsync`, nor property `System.Windows.Media.Imaging.BitmapDecoder.BitmapPixelFormat` – Harald Coppoolse Oct 13 '20 at 14:12
1

It depends on your definition of grayscale.

You may think that grayscale is a matter of pixel format. In this case, you'll have to find an alternative to PixelFormat in UWP, if it exists at all (I don't really know).

But you may also think differently.

Can an image with a 32-bit ARGB pixel format be grayscale? Suppose you scan each pixel and they are all on the grayscale line, like this:

0x000000
0x010101
0x020202
...
0xfefefe
0xffffff

The pixel format allows for 16 million combinations, but only the 256 gray ones are actually used.

By your own convention you may say that this is still a grayscale image, because it can be converted to one without loss of information.

If you read me correctly, you'll see an answer to your question that does not require the PixelFormat property to exist, but is rather expensive to compute.

pid
  • 11,472
  • 6
  • 34
  • 63