// import this // using System.Runtime.InteropServices; privateunsafebyte[] BmpToBytes_Unsafe (Bitmap bmp) ...{ BitmapData bData = bmp.LockBits(new Rectangle (new Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); // number of bytes in the bitmap int byteCount = bData.Stride * bmp.Height; byte[] bmpBytes =newbyte[byteCount]; // Copy the locked bytes from memory Marshal.Copy (bData.Scan0, bmpBytes, 0, byteCount); // don't forget to unlock the bitmap!! bmp.UnlockBits (bData); return bmpBytes; }
还原方法
privateunsafe 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 object Marshal.Copy (bmpBytes, 0, bData.Scan0, bmpBytes.Length); bmp.UnlockBits(bData); return bmp; }
方法2 通过将位图文件写入内存流的方式获取byte[]
// Bitmap bytes have to be created via a direct memory copy of the bitmap privatebyte[] BmpToBytes_MemStream (Bitmap bmp) ...{ MemoryStream ms =new MemoryStream(); // Save to memory using the Jpeg format bmp.Save (ms, ImageFormat.Jpeg); // read to end byte[] bmpBytes = ms.GetBuffer(); bmp.Dispose(); ms.Close(); return bmpBytes; } //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; }
方法3 使用序列化的方式获得位图的byte[]
// import these // using System.Runtime.Serialization; // using System.Runtime.Serialization.Formatters.Binary; privatebyte[] BmpToBytes_Serialization (Bitmap bmp) ...{ // stream to save the bitmap to MemoryStream ms =new MemoryStream(); BinaryFormatter bf =new BinaryFormatter(); bf.Serialize (ms, bmp); // read to end byte[] bmpBytes = ms.GetBuffer(); bmp.Dispose(); ms.Close(); return bmpBytes; } private Bitmap BytesToBmp_Serialized (byte[] bmpBytes) ...{ BinaryFormatter bf =new BinaryFormatter (); // copy the bytes to the memory MemoryStream ms =new MemoryStream (bmpBytes); return (Bitmap)bf.Deserialize(ms); }