【问题标题】:Access to bytes array of a Bitmap访问位图的字节数组
【发布时间】:2012-10-11 13:57:42
【问题描述】:

1- 在 Windows CE 中,我在 C# 中有一个位图对象。

2- 我在 extern dll 中有一个 C 函数,它期望指向字节数组的指针作为参数,该字节数组表示 RGB565 格式、宽度和高度的图像。此函数将使用此字节数组。

所以我需要传递Bitmap对象的字节数组指针,但是我可以找到一种实用的方法来获取这个指针。一种方法是使用内存流或其他方式将此位图转换为字节数组,但它会创建一个新的字节数组,因此我会将对象、位图和字节数组都保存在内存中,但我不想要它因为可用内存很少,所以我需要访问位图对象的字节数组,而不是创建一个新的字节数组。

谁能帮帮我?

【问题讨论】:

    标签: c# c++ c bitmap


    【解决方案1】:

    你可以在图像是你的位图的地方做这样的事情:

    Rectangle area = (new Rectangle(0, 0, image.width, image.height));
    BtimapData bitmapData = image.LockBits(area, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    stride = bitmapData.Stride;
    IntPtr ptr = bitmapData.Scan0;
    

    我了解您不想将位图的 RGB 值复制到另一个数组,但这是最好的解决方案。只有在 C 代码中绘制时,该数组才会在内存中。我在 Windows Professional 6 中使用了类似的方法,它并没有引入很多开销。有许多 FastBitmap 实现可用。您可以在stackoverflowimplementation 上查看此问题

    【讨论】:

      【解决方案2】:

      您可以使用不安全的代码来获取位图数据指针。

      使用以下代码:

      var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
      var bmpData =
          bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
          bmp.PixelFormat);
      
      IntPtr ptr = bmpData.Scan0;
      
      byte* bmpBytes = (byte*)ptr.ToPointer();
      

      其中bmp 是您的Bitmap 对象。

      你也可以做相反的事情:

      ptr = new IntPtr(b);
      
      bmpData.Scan0 = ptr;
      

      【讨论】:

        【解决方案3】:

        感谢“NikolaD”和“oxilumin”的回复,我可以解决我的问题。

        当我使用 RGB565 时,代码是:

        imgMap.Image = new Bitmap(imgMap.Width, imgMap.Height, PixelFormat.Format16bppRgb565);
        Rectangle area = (new Rectangle(0, 0, imgMap.Width, imgMap.Height));
        BitmapData bitmapData = ((Bitmap)imgMap.Image).LockBits(area, ImageLockMode.ReadWrite, PixelFormat.Format16bppRgb565);
        IntPtr ptrImg = bitmapData.Scan0;
        

        在哪里: imgMap 是一个图片框

        再次感谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多