使用内存回流的方法来实现将image的内容转换为 byte[]
在今天的开发中老大不知道怎么突发奇想,要使用Image的Byte数据。当时使用老几种方式效果均不理想,最后发现其实可以使用内存回流的方式来实现。多的不说老,马上贴上代码:
/// <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;
}
/// 将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();
}
/// 将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();
}