Byte[]与图片互相转换,保存到本地

来源:互联网 发布:2017大数据概念股龙头 编辑:程序博客网 时间:2024/05/21 12:42
//图片路径转换为byte[]
public byte[] GetPictureData(string imagePath)
{
FileStream fs = new FileStream(imagePath, FileMode.Open);
byte[] byteData = new byte[fs.Length];
fs.Read(byteData, 0, byteData.Length);
fs.Close();
return byteData;
}
//byte[]格式转为图片
public static Image BytesToImage(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
Image img = Image.FromStream(ms);
return img;
}
示例:
string picpath = Server.MapPath("~/images/hn.jpg");
byte[] photo = GetPictureData(picpath); //调用方法,转换为byte[]
Image image1 = BytesToImage(photo); //byte[]转换为图片
//保存图片到本地 方法一
System.Drawing.Bitmap image = new System.Drawing.Bitmap(image1);
string imgname = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
string path = "~/images/" + imgname;
image.Save(Server.MapPath(path));
this.img1.ImageUrl = path;
//保存图片到本地 方法二
string path = Server.MapPath("~/images").TrimEnd('\\') + @"\";//转为物理路径
System.IO.FileStream fs = new System.IO.FileStream(path + "123.jpg", System.IO.FileMode.Create);//注意123.jpg为你的图片名称

System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
bw.Write(photo, 0, photo.Length);
fs.Flush();//数据写入图片文件
fs.Close();

示例:从数据库读取数据保存到本地照片
DataTable dt = pager.GetTableView("tmp", " 1=1 ");
for (int i = 0; i < dt.Rows.Count; i++)
{
byte[] photo = new byte[0];
string imgname = "";
if (!string.IsNullOrEmpty(dt.Rows[i]["photo"].ToString()))
{
photo = (byte[])dt.Rows[i]["photo"];//读取第一个图片的位流
int ArraySize = photo.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限,用作读取流的上限
imgname = DateTime.Now.ToString("yyyyMMddhhmmss") + i + ".jpg";
//string path = Server.MapPath("~/images").TrimEnd('\\') + @"\";//项目路径转为物理路径
string path = "F:\\pic\\".TrimEnd('\\') + @"\";//物理路径
System.IO.FileStream fs = new System.IO.FileStream(path + imgname, System.IO.FileMode.Create);//注意123.jpg为你的图片名称
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
bw.Write(photo, 0, photo.Length);
fs.Flush();//数据写入图片文件
fs.Close();
string sql = "insert into tmpxx(aab004,aac003,aae135,photo) values ('" + dt.Rows[i]["aab004"].ToString() + "','" + dt.Rows[i]["aac003"].ToString() + "','" + dt.Rows[i]["aae135"].ToString() + "','" + "/UploadFiles/UserIcon/2016/1025/" + imgname + "')";
int m = pager.RunSql(sql);
}
else {
string sql = "insert into tmpxx(aab004,aac003,aae135,photo) values ('" + dt.Rows[i]["aab004"].ToString() + "','" + dt.Rows[i]["aac003"].ToString() + "','" + dt.Rows[i]["aae135"].ToString() + "','')";
int m = pager.RunSql(sql);
}

0 0
原创粉丝点击