如何从位图中获取每像素比特数(Bitsperpixel)

25

我有一个需要给出位图的每像素比特数(bits per pixel)的第三方组件。

最好的获取"bits per pixel"的方法是什么?

我的起点是下面这个空白方法:

public int GetBitsPerPixelMethod( system.drawing.bitmap bitmap )
{
   //return BitsPerPixel;
}
6个回答

107

与其自己创建一个函数,我建议使用框架中已有的函数:

Image.GetPixelFormatSize(bitmap.PixelFormat)

12
这应该是这个问题的被采纳答案。 - Richard Ev
2
感谢您的分享。 - datoml

8

1
欢迎来到SO。好的回答应该包括可测试的代码答案,明确它所需要的假设条件(.NET版本),以及链接到文档的信息。你可能可以在回答中使用问题中提供的现有bitmap变量/函数参数,而不是创建一个新的(source)。 - poplitea

4
是什么意思?


1
使用Pixelformat属性,它会返回一个Pixelformat枚举,该枚举可以具有像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;      
 }

0

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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接