C#中Image与Byte数组互转
代码如下:
/// <summary> /// 将Image转化为Byte数组 /// </summary> /// <param name="img">要转化的图像</param> /// <returns>返回转化后的Byte字节数组</returns> public byte[] GetByteImage(Image img) { byte[] bt = null; if (!img.Equals(null)) { using (MemoryStream mostream = new MemoryStream()) { Bitmap bmp = new Bitmap(img); bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//将图像以指定的格式存入缓存内存流 bt = new byte[mostream.Length]; mostream.Position = 0;//设置留的初始位置 mostream.Read(bt, 0, Convert.ToInt32(bt.Length)); } } return bt; } /// <summary> /// 将Byte字节数组转化为Image图像 /// </summary> /// <param name="bytes">Byte字节数组</param> /// <returns>返回转化后的图像</returns> public static Image GetImageByBytes(byte[] bytes) { Image photo = null; using (MemoryStream ms = new MemoryStream(bytes)) { ms.Write(bytes, 0, bytes.Length); photo = Image.FromStream(ms, true); } return photo; }