Welcome 微信登录

首页 / 网页编程 / ASP.NET / 从图像转换到byte[]数组的几种方法

从图像转换到byte[]数组的几种方法2011-11-13 博客园 奇拉
// 性能最高,其数组和像素一一对应public static void test1(Image img){Bitmap bmp = new Bitmap(img);BitmapData bitmapData = bmp.LockBits(new Rectangle(new Point(0, 0), img.Size), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);byte[] BGRValues = new byte[bitmapData.Stride * bitmapData.Height];IntPtr Ptr = bitmapData.Scan0;System.Runtime.InteropServices.Marshal.Copy(Ptr, BGRValues, 0, BGRValues.Length);bmp.UnlockBits(bitmapData);}// 性能较低,数组内容较少,内容未知public static void test2(Image img){System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();byte[] btImage1 = new byte[0];btImage1 = (byte[])ic.ConvertTo(img, btImage1.GetType());}// 性能较低,数组内容为图片格式内容,格式未知public static void test3(Image img){System.IO.MemoryStream ms = new System.IO.MemoryStream();img.Save(ms,ImageFormat.Bmp);byte[] byteImage = new Byte[0];byteImage = ms.ToArray();}
下面说说他们的特点

test1和test3性能十分接近,test2性能要比前2个明显低一些,应为它们都是内存操作,当然快了。

test3在单次各种测试候都比test1要快一点点,真的是一点点,但是在做5000次测试时,test3就明显 拉开了距离;

那么可以看出test3在某条语句上耗时了,但可能不是数组操作,比较在内存里,我个人认为是 ImageFormat编码的耗时,当然,你用ImageFormat.Png获得的byte[]长度明显变短,

但是耗时也明显增加。

test2一如既往的明显慢。