我有一个需要给出位图的每像素比特数(bits per pixel)的第三方组件。
最好的获取"bits per pixel"的方法是什么?
我的起点是下面这个空白方法:
public int GetBitsPerPixelMethod( system.drawing.bitmap bitmap )
{
//return BitsPerPixel;
}
与其自己创建一个函数,我建议使用框架中已有的函数:
Image.GetPixelFormatSize(bitmap.PixelFormat)
var source = new BitmapImage(new System.Uri(pathToImageFile));
int bitsPerPixel = source.Format.BitsPerPixel;
以上代码要求至少使用.NET 3.0
http://msdn.microsoft.com/zh-cn/library/system.windows.media.imaging.bitmapimage.aspx
bitmap
变量/函数参数,而不是创建一个新的(source
)。 - popliteaFormat24bppRgb
这样的值,显然每个像素为24位,因此您应该能够执行以下操作:switch(Pixelformat)
{
...
case Format8bppIndexed:
BitsPerPixel = 8;
break;
case Format24bppRgb:
BitsPerPixel = 24;
break;
case Format32bppArgb:
case Format32bppPArgb:
...
BitsPerPixel = 32;
break;
default:
BitsPerPixel = 0;
break;
}
Bitmap.PixelFormat 属性将告诉您位图具有的像素格式类型,从而您可以推断每个像素的位数。我不确定是否有更好的方法来获取此信息,但至少天真的方法是这样的:
var bitsPerPixel = new Dictionary<PixelFormat,int>() {
{ PixelFormat.Format1bppIndexed, 1 },
{ PixelFormat.Format4bppIndexed, 4 },
{ PixelFormat.Format8bppIndexed, 8 },
{ PixelFormat.Format16bppRgb565, 16 }
/* etc. */
};
return bitsPerPixel[bitmap.PixelFormat];