最近做项目,要将客户端图片转化为二进制,保存到数据库中。
将图片转化为二进制:
(1)通过图片路径进行转化
private byte[] reDyte(string strPath)
{
// 以二进制方式读文件
FileStream fsMyfile = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
// 创建一个二进制数据流读入器,和打开的文件关联
BinaryReader brMyfile = new BinaryReader(fsMyfile);
// 把文件指针重新定位到文件的开始
brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
byte[] bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
// 关闭以上new的各个对象
brMyfile.Close();
return bytes;
}
(2)通过图片对象进行转化
private static byte[] Getbyte(Image img)
{
MemoryStream stream = new MemoryStream();
//img.Save(stream,ImageFormat.Jpeg);
byte[] mydata = new byte[stream.Length];
mydata = stream.ToArray();
stream.Close();
return mydata;
}
(3)将二进制转化为图片
private System.Drawing.Image getImage(byte[] fileData)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms); return img;
}
(4)利用image显示
private void ImgShow(WorkerInfo workerInfo)
{
string strPicture = "";
System.Drawing.Image imgPictureShow = getImage(workerInfo.Photo);
//定义文件名
strPicture = "Picture" + DateTime.Now.ToString("yyMMddhhmmss");
imgPictureShow.Save(Server.MapPath("~/pic/") + strPicture + "jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//显示文件
imgPicture.ImageUrl = "pic/" + strPicture + ".jpg";