繁体   English   中英

访问位图的字节数组

[英]Access to bytes array of a Bitmap

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

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

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

有人可以帮助我吗?

您可以执行以下操作,其中图像是您的位图:

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实现。 您可以在stackoverflow或此实现上检查此问题

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

使用以下代码:

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;

多亏了“ 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是一个PictureBox

再次感谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM