将位图对象转换为字节数组的最快方法 [英] Fastest method to convert bitmap object to byte array
问题描述
您好,
我们有一个基于高容量交易的网络服务。需要将内存位图对象转换为字节数组。可以请任何人建议最好的方法。我能想到的几种方式是:
1。使用TypeDescriptor
byte [] bytes =(byte [])TypeDescriptor.GetConverter(bmp).ConvertTo(bmp,typeof(byte []));
2。使用内存流
MemoryStream ms = new MemoryStream();
//使用Jpeg格式保存到内存
bmp.Save(ms,ImageFormat.Jpeg);
//读取结束
byte [] bmpBytes = ms.GetBuffer();
bmp.Dispose();
ms.Close();
请根据表现建议从上面或任何新方式的最佳方式。
谢谢。
Aman。
您好,
感谢您的帖子。
根据我的经验, Bitmap.LockBits方法 ( http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx ) 是这种情况下的关键概念。例如:
private byte [] GetRGBValues(Bitmap bmp)
{
//锁定位图的位。
Rectangle rect = new Rectangle(0,0,bmp.Width,bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect,System.Drawing.Imaging.ImageLockMode.ReadOnly,
bmp.PixelFormat);
//获取第一行的地址。
IntPtr ptr = bmpData.Scan0;
//声明一个数组来保存位图的字节。
int bytes = bmpData.Stride * bmp.Height;
byte [] rgbValues = new byte [bytes];
//将RGB值复制到数组中。
System.Runtime.InteropServices.Marshal.Copy(ptr,rgbValues,0,bytes); bmp.UnlockBits(bmpData);
返回rgbValues;
}希望这会有所帮助。
此致,
Yasser
Hello,
We have a high volume transaction based webservice. There is a need to convert the inmemory bitmap object into byte array. Can anyone please suggest best way to do it. Couple of ways that I can think of are:
1. Using the TypeDescriptor
byte[] bytes = (byte[])TypeDescriptor.GetConverter(bmp).ConvertTo(bmp, typeof(byte[]));
2. Using the Memory Stream
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();
Please suggest the best way from above or any new one as per performance.
Thanks.
Aman.
Hi,
Thanks for your post.
In my experience, Bitmap.LockBits Method (http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx) is the key concept in this condition. For example:
private byte[] GetRGBValues(Bitmap bmp) { // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);bmp.UnlockBits(bmpData); return rgbValues; }Hope this helps.
Sincerely,
Yasser
这篇关于将位图对象转换为字节数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!