【问题标题】:Convert a bitmap into 2D byte array in C#?在 C# 中将位图转换为二维字节数组?
【发布时间】:2018-01-05 17:18:20
【问题描述】:

我一直在使用 AForge.NET 框架开发一个项目。在我的项目中,我一直在尝试从灰度位图中获取 2D 字节数组。在本网站和其他论坛上发布了一些关于此主题的解决方案。但我还没有得到真正的结果。例如,我使用了该代码:

public static byte[] ImageToByte2(Image img)
{
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }
    return byteArray;
}

在这个“MemoryStream”方法之后,我考虑过将这个字节数组转换为二维。但是,当我使用 4*8 位图测试此代码示例时,它会将 1100 个值返回到 byteArray。这正常吗?我错过了哪里?

【问题讨论】:

    标签: c# arrays image 2d


    【解决方案1】:

    .NET Image 类用作两种类型图像的接口:Bitmap 图像和Metafile 图像。后者由一系列用于绘制某些东西的指令组成,而不是像位图这样的像素数组。如果您查看Bitmap class itself,有一对LockBits 方法可以让您提取图像的像素数据。在 Bitmap 类的链接参考的底部,甚至还有一个如何执行此操作的示例。

    【讨论】:

      【解决方案2】:

      请使用以下方法

      public static byte[,] ImageTo2DByteArray(Bitmap bmp)
          {
              int width = bmp.Width;
              int height = bmp.Height;
              BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
      
              byte[] bytes = new byte[height * data.Stride];
              try
              {
                  Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
              }
              finally
              {
                  bmp.UnlockBits(data);
              }
      
              byte[,] result = new byte[height, width];
              for (int y = 0; y < height; ++y)
                  for (int x = 0; x < width; ++x)
                  {
                      int offset = y * data.Stride + x * 3;
                      result[y, x] = (byte)((bytes[offset + 0] + bytes[offset + 1] + bytes[offset + 2]) / 3);
                  }
              return result;
          }
      

      【讨论】:

      • 您可能会考虑以字节以外的其他类型返回二维数组,因为平均字节会隐藏一些信息。还要考虑包括 Alpha 通道 (RGBA)。
      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      相关资源
      最近更新 更多