问题
I have a C# .NET library that grabs frames from a camera. I need to send those frames to a native application that takes images from an unsigned char*
.
I initially take the frames as System::Drawing::Bitmap
.
So far I can retrieve a byte[]
from the Bitmap
. My test is done with an image of resolution 400*234, I should be getting 400*234*3 bytes to get to the 24bpp a RGB image requires.
However, I'm getting a byte[]
of size 11948.
This is how I convert from Bitmap
to byte[]
:
private static byte[] ImageToByte(Bitmap img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
What is the proper way to convert from System::Drawing::Bitmap
to RGB unsigned char*
?
回答1:
This has to be done using the lockBits method, here is a code example:
Rectangle rect = new Rectangle(0, 0, m_bitmap.Width, m_bitmap.Height);
BitmapData bmpData = m_bitmap.LockBits(rect, ImageLockMode.ReadOnly,
m_bitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = Math.Abs(bmpData.Stride) * m_bitmap.Height;
byte[] rgbValues = new byte[bytes];
Marshal.Copy(ptr, rgbValues, 0, bytes);
m_bitmap.UnlockBits(bmpData);
GCHandle handle = GCHandle::Alloc(rgbValues, GCHandleType::Pinned);
unsigned char * data = (unsigned char*) (void*) handle.AddrOfPinnedObject();
//do whatever with data
来源:https://stackoverflow.com/questions/18407349/systemdrawingbitmap-to-unsigned-char