Deulis
Deulis

Reputation: 474

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?

Upvotes: 0

Views: 2171

Answers (3)

Deulis
Deulis

Reputation: 474

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

Upvotes: 0

oxilumin
oxilumin

Reputation: 4833

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;

Upvotes: 1

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

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

Upvotes: 2

Related Questions