C# 如何从位图中获取 Bitsperpixel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1126967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:49:47  来源:igfitidea点击:

how to get Bitsperpixel from a bitmap

c#drawing

提问by jason clark

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

我有一个 3rd 方组件,它要求我从位图中给它位像素。

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

采纳答案by schnaader

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

使用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;      
 }

回答by IRBMe

The Bitmap.PixelFormatproperty 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:

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

回答by Scott

What about Image.GetPixelFormatSize()?

Image.GetPixelFormatSize() 怎么样?

回答by CodeAndCats

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

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

Image.GetPixelFormatSize(bitmap.PixelFormat)

回答by Matthew Johnson

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

The code above requires at least .NET 3.0

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

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

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