[Reprint] converting a bitmap to a byte array

Source: Internet
Author: User
This comes from my own l33t hax0r Skillz
If you 've got a better way, say so

Method 1 just copies the bitmap bytes from memory
Method 2 actually saves the image and writes any image headers and whatnot using a proper image format, and then converts the written data to a byte array
Method 3 saves the objects data using serialization (very useless just serialize to file or something... included for the heck of it)

The l33test way in my opinion is using unsafe code:

Method 1: Unsafe code, locking the bitmap and using the marshal class

Code:
// import this // using System.Runtime.InteropServices;private unsafe byte[] BmpToBytes_Unsafe (Bitmap bmp){BitmapData bData = bmp.LockBits(new Rectangle (new Point(), bmp.Size),ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);// number of bytes in the bitmapint byteCount = bData.Stride * bmp.Height;byte[] bmpBytes = new byte[byteCount];// Copy the locked bytes from memoryMarshal.Copy (bData.Scan0, bmpBytes, 0, byteCount);// don't forget to unlock the bitmap!!bmp.UnlockBits (bData);return bmpBytes;}

In most cases this works fine, because your bitmap doesn't have an alpha channel. But if it does, and you want to preserve it, then useFormat32bppArgbIn the fist line when locking the bitmap.
I wish I cocould think of a way of doing this without locking the bitmap (ie, you cocould use GCHandle. alloc () and then call Marshal. copy () using the created handle, but the problem is I wouldnt know the size of the bitmap without locking it's bits and the stored Al. copy () function needs to know the size ).

Reversing this process is a bit uugly, as you need to know the dimensions of the bitmap. Code:

private unsafe Bitmap BytesToBmp (byte[] bmpBytes, Size imageSize){Bitmap bmp = new Bitmap (imageSize.Width, imageSize.Height);BitmapData bData  = bmp.LockBits (new Rectangle (new Point(), bmp.Size),ImageLockMode.WriteOnly,PixelFormat.Format24bppRgb);// Copy the bytes to the bitmap objectMarshal.Copy (bmpBytes, 0, bData.Scan0, bmpBytes.Length);bmp.UnlockBits(bData);return bmp;}

OK that was if you wanted to have exactly the same bytes as in the memory There are two other ways I can think. note that these won't produce the exact copy of the bitmap bits from the memory

Method 2: using a memory stream
This just asks the. Save () method to save the bytes to a memory stream, then you can get the written bytes to the stream:

Code:
// Bitmap bytes have to be created via a direct memory copy of the bitmapprivate byte[] BmpToBytes_MemStream (Bitmap bmp){MemoryStream ms = new MemoryStream();// Save to memory using the Jpeg formatbmp.Save (ms, ImageFormat.Jpeg);// read to endbyte[] bmpBytes = ms.GetBuffer();bmp.Dispose();ms.Close();return bmpBytes;}

Converting that back to a bitmap is easy. Code:

//Bitmap bytes have to be created using Image.Save()private Image BytesToImg (byte[] bmpBytes){MemoryStream ms = new MemoryStream(bmpBytes);Image img = Image.FromStream(ms);// Do NOT close the stream!return img;}

Method 3: using serialization
I can't see any reason why someone wocould use this method, it's very stupid including it just for referencecode:

// import these// using System.Runtime.Serialization;// using System.Runtime.Serialization.Formatters.Binary;private byte[] BmpToBytes_Serialization (Bitmap bmp){// stream to save the bitmap toMemoryStream ms = new MemoryStream();BinaryFormatter bf = new BinaryFormatter();bf.Serialize (ms, bmp);// read to endbyte[] bmpBytes = ms.GetBuffer();bmp.Dispose();ms.Close();return bmpBytes;}private Bitmap BytesToBmp_Serialized (byte[] bmpBytes){BinaryFormatter bf = new BinaryFormatter ();// copy the bytes to the memoryMemoryStream ms = new MemoryStream (bmpBytes);return (Bitmap)bf.Deserialize(ms);}

Big note: If you use any of these methods, then you have to use both functions presented in the method together. for example you can't get the bitmap bytes using method 1, and then call method2's function bytestoimg ()

Also, a bit after I wrote that method 1, I realized that there was an API for doing this. it's maybe the best method but there is a turn down: You have to use reflection to retreive the bitmap handle in order to use it with the API function:
Method 4: Using Reflection and API
I just tell you the APIs to retreive the bitmap handle you can use thiscode:

private IntPtr getImageHandle (Image img){FieldInfo fi = typeof(Image).GetField("nativeImage", BindingFlags.NonPublic | BindingFlags.Instance);if (fi == null)return IntPtr.Zero;return (IntPtr)fi.GetValue (img);}

TheGetBitmapBitsAPI seems to be the easy way out, but apparently it's just there for 16bit compatibility. You shoshould useGetDIBitsInstead. If you end up using that method, please post your code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.