25

I have a 3rd party component which requires me to give it the bitsperpixel from a bitmap.

What's the best way to get "bits per pixel"?

My starting point is the following blank method:-

public int GetBitsPerPixelMethod( system.drawing.bitmap bitmap )
{
   //return BitsPerPixel;
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
jason clark
  • 829
  • 2
  • 11
  • 23

6 Answers6

107

Rather than creating your own function, I'd suggest using this existing function in the framework:

Image.GetPixelFormatSize(bitmap.PixelFormat)
CodeAndCats
  • 7,508
  • 9
  • 42
  • 60
8
var source = new BitmapImage(new System.Uri(pathToImageFile));
int bitsPerPixel = source.Format.BitsPerPixel;

The code above requires at least .NET 3.0

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 1
    Welcome to SO. Good answer: testable code-answer, stated assumption (.NET-version) for it to work, and link to documentation. You could probably have used the existing `bitmap` variable/function-argument supplied in the question instead of creating a new one (`source`) in your answer, though. – poplitea Sep 29 '12 at 11:57
4

What about Image.GetPixelFormatSize()?

Scott
  • 121
  • 1
  • 6
2

Try:

Bitmap.PixelFormat

See possible values of the PixelFormat property.

TWA
  • 12,756
  • 13
  • 56
  • 92
1

Use the Pixelformat property, this returns a Pixelformat enumeration which can have values like f.e. Format24bppRgb, which obviously is 24 bits per pixel, so you should be able to do something like this:

switch(Pixelformat)       
  {
     ...
     case Format8bppIndexed:
        BitsPerPixel = 8;
        break;
     case Format24bppRgb:
        BitsPerPixel = 24;
        break;
     case Format32bppArgb:
     case Format32bppPArgb:
     ...
        BitsPerPixel = 32;
        break;
     default:
        BitsPerPixel = 0;
        break;      
 }
schnaader
  • 49,103
  • 10
  • 104
  • 136
0

The Bitmap.PixelFormat property will tell you the type of pixel format that the bitmap has, and from that you can infer the number of bits per pixel. I'm not sure if there's a better way of getting this, but the naive way at least would be something like this:

var bitsPerPixel = new Dictionary<PixelFormat,int>() {
    { PixelFormat.Format1bppIndexed, 1 },
    { PixelFormat.Format4bppIndexed, 4 },
    { PixelFormat.Format8bppIndexed, 8 },
    { PixelFormat.Format16bppRgb565, 16 }
    /* etc. */
};

return bitsPerPixel[bitmap.PixelFormat];
IRBMe
  • 4,335
  • 1
  • 21
  • 22