很多时候我们在存储图片的时候,都是用的二进制文件,下面的函数将实现图片与二进制之间的转化,注意这里要用到两个C#命名空间:
using System.Drawing;
using System.IO;
/// <summary>
/// 将图片转化为二进制,path 图片路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static byte[] ImgToByte(String path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
return imgBytesIn;
}
/// <summary>
/// 将图片二进制文件,转化为Image方便显示图片
/// </summary>
/// <param name="imgBytesIn"></param>
/// <returns></returns>
public static Image ImgByByte(byte[] imgBytesIn)
{
MemoryStream ms = new MemoryStream(imgBytesIn);
return Image.FromStream(ms);
}