Convert Bitmap to Byte[]

  • Thread starter Thread starter Sergio Florez M.
  • Start date Start date
S

Sergio Florez M.

How can I convert a Bitmap to a byte array? I've searched all over and none
of the code samples I've managed to find work.

Actually, I just need to create a Byte array starting from an Image object.
 
Actually, I just need to create a Byte array starting from an Image
object.

You can serialize your object using the 'BinaryFormatter' and read the
bytes from the 'Stream'.

Joannes
 
Image have more private fields than just the image data. If you use a
BinaryFormatter
you'll get a bunch of .NET serialization primitives in the stream and you won't
be able
to easily get at the data. This is a fairly decent attempt at quickly turning a
bitmap into
a binary stream where you can get access to it's data though.

The primary method is to use LockBits
 
Assuming image is an Image object:

MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] bytes = stream.ToArray();
 
Heres some sample code taht you coudl use.. you will need a unsage code
block for this, and compile it with the unsafe option
//Lock the images in memory so we can access them directly
originalBitmapData = originalBitmap.LockBits(new
Rectangle(0, 0, originalBitmap.Width, originalBitmap.Height),
ImageLockMode.ReadOnly, originalBitmap.PixelFormat);
comparisonBitmapData = comparisonBitmap.LockBits(new
Rectangle(0, 0, comparisonBitmap.Width, comparisonBitmap.Height),
ImageLockMode.ReadOnly, comparisonBitmap.PixelFormat);
outputBitmapData = outputBitmap.LockBits(new Rectangle(0, 0,
outputBitmap.Width, outputBitmap.Height), ImageLockMode.WriteOnly,
outputBitmap.PixelFormat);

//Get pointers to the first byte in each image
byte* originalScanPtr = (byte*)originalBitmapData.Scan0;
 
Back
Top