【问题标题】:Number of channels in System.Drawing.Bitmap C#System.Drawing.Bitmap C# 中的通道数
【发布时间】:2019-01-24 09:12:15
【问题描述】:

我正在用 C# 编码,并以这种方式加载图像:

// loading image
string imageFileName = "myImage.jpg";
Bitmap bmp = new Bitmap(imageFileName, false);

// trying to display color so that I know how many channels I have
// except it always displays 4 values, whether I have 1, 3 or 4 channels
Color color = bmp.GetPixel(0, 0);
Console.WriteLine(color.ToString());

// locking the bitmap's bits
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

// doing stuff that requires me to know the number of channels of the image, amongst other things

// unlocking the bitmap's bits
bmp.UnlockBits(bmpData);

我需要知道图像中的通道数(通常是灰度 (1)、RGB (3) 或 RGBA (4)),但我不知道这些信息是如何存储的。

编辑: 我不想强制像素格式。我正在尝试加载图像,并在程序上找出我加载的图像中的通道数。

【问题讨论】:

  • 执行此操作的最简单且通常最快的方法是简单地强制像素格式,以便您的代码无论实际通道数如何都能正常工作。只有一种像素格式是最好的,它是 32bppArgb。这使您可以使用 int* 来寻址像素,这是读取和写入的最快方式。作为对比,您从 JPEG 图像中获得的 24bppRgb 非常尴尬,您必须使用一个字节*,并且每个像素需要 3 次读/写。那很慢。但是,如果需要转换,则不是免费的。你必须测量。
  • 我不确定它是否能回答我的问题。我不想强制像素格式。我只是在尝试加载图像,并在程序上找出我加载的图像中的通道数。
  • 我知道你问了什么,我的明确建议是不必问。
  • 是的,我终于明白你和TaW在说什么了(这就是我删除评论的原因)。 C# 不是我的主要语言,所以我很难弄清楚。

标签: c# image channels


【解决方案1】:

有一个PixelFormat 属性,您可以在MSDN 上阅读。

如果需要,您可以结合:GetPixelFormatSize 它来获取每个像素的字节数。

【讨论】:

  • 是的,我只需要在我的代码中添加System.Drawing.Image.GetPixelFormatSize(bmp.PixelFormat)
【解决方案2】:

创作:

您需要使用带有 PixelFormat 参数的overload of the Bitmap contructor

用法:

bitmap.PixelFormat 属性会告诉你你有什么。

Here is more info about the PixelFormats

【讨论】:

  • 虽然我不需要使用 Bitmap 构造函数的重载(特别是因为它们都没有采用文件名和像素格式),但我需要知道图像的通道数我从磁盘加载,Bitmap.PixelFormat 属性确实是我正在寻找的。我在问这个问题之前自己看时忽略了它,因为我期待像 Bitmap.ChannelCount 之类的东西。谢谢你的回答。
猜你喜欢
  • 2016-04-10
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多