【问题标题】:C# Using BinaryReader to read color byte values of a bitmap imageC# 使用 BinaryReader 读取位图图像的颜色字节值
【发布时间】:2014-11-14 01:48:38
【问题描述】:

我正在使用 BinaryReader 读取图像的字节,但在尝试使用 BinaryReader 读取位图图像的 ARGB 值时遇到了一些问题。谁能建议我可以获取位图图像中每个像素的字节值的方法?

提前致谢

【问题讨论】:

  • 简单方法:使用Bitmap的GetPixel(x, y)方法(慢),使用指针读取位图(高级,但快)
  • 你知道使用 BinaryReader 而不是位图函数的方法吗?
  • codeproject.com/Questions/308076/… 请阅读第二个解决方案
  • “我在尝试使用 BinaryReader 读取位图图像的 ARGB 值时遇到一些问题。”到目前为止你有什么代码?
  • @IllidanS4 大声笑,位图文件格式不是仅包含像素的纯格式。它包含许多元数据,如格式、bpp、大小等,因此您应该忽略“垃圾”数据并开始读取实际数据,但如果不知道实际的 .bmp 文件结构,这是不可能的。

标签: c# bitmap binaryreader


【解决方案1】:

简单的方法是使用不安全的上下文并锁定一些位。过于简单的示例:

unsafe
{
    var bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);

    byte* first = (byte*)bitmapData.Scan0;   
    byte a = first[0];
    byte r = first[1];
    byte g = first[2];
    byte b = first[3];

    ...

    bmp.UnlockBits(bitmapData);
}

但是,如果您仍然需要使用 BinaryReader 并且您知道每个像素有多少字节,则可以跳过标题(您可以在 @Bradley_Ufffner 的链接中找到它的长度)并访问字节。

【讨论】:

    【解决方案2】:

    您需要在此处学习 BMP 文件格式:http://en.wikipedia.org/wiki/BMP_file_format 正确读取文件将涉及从标题中找出像素格式并据此正确解析数据。该文件可能是颚化的,在这种情况下,您需要读出颜色表数据并使用它将像素映射到实际颜色。像素数据也可能会被压缩,并且必须根据标头中的值进行提取。

    这不会是一个简单的项目,这就是发明图形库的原因。

    【讨论】:

      【解决方案3】:

      如果您需要使用 BinaryReader 读取位图的像素数据,请尝试UnmanagedMemoryStream

      Bitmap bmp = new Bitmap("img.bmp");
      var bits = bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
      try{
          unsafe{
              using(Stream bmpstream = new UnmanagedMemoryStream((byte*)bits.Scan0, bits.Height*bits.Stride))
              {
                  BinaryReader reader = new BinaryReader(bmpstream);
                  for(int y = 0; y < bits.Height; y++)
                  {
                      bmpstream.Seek(bits.Stride*y, SeekOrigin.Begin);
                      for(int x = 0; x < bits.Width; x++)
                      {
                          byte b = reader.ReadByte();
                          byte g = reader.ReadByte();
                          byte r = reader.ReadByte();
                          byte a = reader.ReadByte();
                      }
                  }
              }
          }
      }finally{
          bmp.UnlockBits(bits);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-10
        • 2012-06-07
        • 2013-03-18
        • 2014-08-03
        • 2010-09-16
        • 2013-05-07
        • 1970-01-01
        • 2011-07-18
        相关资源
        最近更新 更多