如何从位图获取Bitsperpixel

我有一个第三方组件,它要求我从位图给它bitsperpixel。

获得“每像素位数”的最佳方法是什么?

我的出发点是以下空白方法: –

public int GetBitsPerPixelMethod( system.drawing.bitmap bitmap ) { //return BitsPerPixel; } 

使用Pixelformat属性 ,这将返回一个Pixelformat枚举 ,其枚举值可能为fe Format24bppRgb ,显然是每像素24位,因此您应该可以执行以下操作:

 switch(Pixelformat) { ... case Format8bppIndexed: BitsPerPixel = 8; break; case Format24bppRgb: BitsPerPixel = 24; break; case Format32bppArgb: case Format32bppPArgb: ... BitsPerPixel = 32; break; default: BitsPerPixel = 0; break; } 

我建议在框架中使用这个现有函数,而不是创建自己的函数:

 Image.GetPixelFormatSize(bitmap.PixelFormat) 
 var source = new BitmapImage(new System.Uri(pathToImageFile)); int bitsPerPixel = source.Format.BitsPerPixel; 

上面的代码至少需要.NET 3.0

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

尝试:

Bitmap.PixelFormat

请参阅PixelFormat属性的可能值 。

那么Image.GetPixelFormatSize()呢?

Bitmap.PixelFormat属性将告诉您位图具有的像素格式类型,从中可以推断出每个像素的位数。 我不确定是否有更好的方法来获得这个,但是天真的方式至少会是这样的:

 var bitsPerPixel = new Dictionary() { { PixelFormat.Format1bppIndexed, 1 }, { PixelFormat.Format4bppIndexed, 4 }, { PixelFormat.Format8bppIndexed, 8 }, { PixelFormat.Format16bppRgb565, 16 } /* etc. */ }; return bitsPerPixel[bitmap.PixelFormat];