为存储和读取方便,经常需要将图片以字节数组形式存储到数据库,或者从数据库读取图片的字节数组数据还原为图片,可以定义一个转换类,方便调用。
public static class Img2Byte
{
/// <summary>
/// 从图像转换为字节数组
/// </summary>
/// <param name="img">Image对象</param>
/// <returns>字节数组</returns>
public static byte[] getByteFromImage(Image img)
{
byte[] imgByte = null;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imgByte = ms.GetBuffer();
}
return imgByte;
}
/// <summary>
/// 从字节数组转换为图像
/// </summary>
/// <param name="imgByte">字节数组</param>
/// <returns>Image对象</returns>
public static Image getImageFromByte(byte[] imgByte)
{
Image img = null;
if (imgByte.Length == 0)
return null;
using (MemoryStream ms = new MemoryStream(imgByte))
{
img = Image.FromStream(ms);
}
return img;
}
/// <summary>
/// 从图片路径转为字节数组
/// </summary>
/// <param name="imgFilePath">图片完整路径</param>
/// <returns>字节数组</returns>
public static byte[] getByteFromImgFile(string imgFilePath)
{
if(!File.Exists(imgFilePath))
return null;
FileStream fs = new FileStream(imgFilePath, FileMode.Open, FileAccess.Read);
long length = fs.Length;
byte[] imgByte = new byte[length];
fs.Read(imgByte, 0, imgByte.Length);
fs.Close();
return imgByte;
}
}
437

被折叠的 条评论
为什么被折叠?



