简体   繁体   中英

Access to bytes array of a Bitmap

1- In Windows CE, I have a Bitmap object in C#.

2- I have a C function in an extern dll that expects as parameters the pointer to a bytes array that represents an image in RGB565 format, width and height. This function will draw on this array of bytes.

So I need to pass the byte array pointer of the Bitmap object, but I can find a practical way to get this pointer. One way is convert this Bitmap into a bytes array using a memory stream or something else, but it will create a new bytes array, so I will keep in memory both object, the Bitmap and the bytes array, but I don't want it because the few available memory, that's why I need to access to the bytes array of the bitmap object, not create a new bytes array.

Anyone can help me?

You can do something like this where image is your Bitmap:

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;

I understand that you don't want to copy RGB values of the Bitmap to another array but that is the best solution. The array is going to be in memory only while drawing in C code. I have used similar approach in Windows Professional 6 and it didn't introduce a lot of overhead. There are many FastBitmap implementations available. You can check this question on stackoverflow or this implementation

You can use unsafe code to acquire a bitmap data pointer.

Use the following code:

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();

where bmp is your Bitmap object.

You also then can do the opposite:

ptr = new IntPtr(b);

bmpData.Scan0 = ptr;

thanks to the response of "NikolaD" and "oxilumin" I could solve my problem.

As I am using RGB565 the code was:

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;

where: imgMap is a PictureBox

thanks again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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