您的位置:首页 > 数据库

C#将照片或图片转化为byte[]存入数据库,从数据库中读照片

2010-09-09 13:22 288 查看
1. 写入数据库:

public static byte[] GetBytesByImage(PictureBox pb)
{
byte[] photo_byte= null;

if (!pb.Image.Equals(null))
{
using (MemoryStream ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(pb.Image);
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
photo_byte = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
bmp.Dispose();
}
}

return photo_byte;
}


2.将实际位置中的照片转化为byte[]类型写入数据库中:

public static byte[] GetBytesByImagePath(string strFile)
{
byte[] photo_byte = null;
using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
photo_byte = br.ReadBytes((int)fs.Length);
}
}

return photo_byte;
}


3. 读取byte[]并转化为图片:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: