Convert Bitmap to Byte[]

  • Thread starter Sergio Florez M.
  • 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.
 
J

Joannes Vermorel

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
 
J

Justin Rogers

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
 
A

Andy Gaskell

Assuming image is an Image object:

MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
Byte[] bytes = stream.ToArray();
 
J

Jeu George

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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top