将Image对象和byte[]互相转换

//需要引入的命名空间
using
System;
using System.IO;
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;
//引入供序列化Image对象使用

//以下为转换方法

//将Image转换为byte[]
public byte[] ConvertImage(Image image)
{
     FileStream fs=new FileStream("imagetemp",FileMode.Create,FileAccess.Write,FileShare.None);
     BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(fs,(object)image);
     fs.Close();
     fs=new FileStream("imagetemp",FileMode.Open,FileAccess.Read,FileShare.None);
     byte[] bytes = new byte[fs.Length];
     fs.Read(bytes,0,(int)fs.Length);
     fs.Close();
     return bytes;
}

//将byte[]转换为Image
public Image ReadImage(byte[] bytes)
{
  FileStream fs=new FileStream("imagetemp1",FileMode.Create,FileAccess.Write,FileShare.None);
  foreach(byte a in bytes)
  {
    fs.WriteByte(a);
  }
     fs.Close();
     fs=new FileStream("imagetemp1",FileMode.Open,FileAccess.Read,FileShare.None);
     BinaryFormatter bf = new BinaryFormatter();
     object obj=bf.Deserialize(fs);   
  fs.Close(); 
  return (Image)obj;
}

/// <summary>
/// 将byte[]转换为Image
/// </summary>
/// <param name="bytes">字节数组</param>
/// <returns>Image</returns>

public Image ReadImage(byte[] bytes)
{
     MemoryStream ms=new MemoryStream(bytes,0,bytes.Length);
     BinaryFormatter bf = new BinaryFormatter();
     object obj=bf.Deserialize(ms);   
  ms.Close(); 
  return (Image)obj;
}
/// <summary>
/// 将Image转换为byte[]
/// </summary>
/// <param name="image">Image</param>
/// <returns>byte[]</returns>

public byte[] ConvertImage(Image image)
{
     MemoryStream ms=new MemoryStream();
     BinaryFormatter bf = new BinaryFormatter();
     bf.Serialize(ms,(object)image);
     ms.Close();
     return ms.ToArray();
}
posted @ 2013-10-08 08:46  金虹巴巴  阅读(323)  评论(0编辑  收藏  举报