标签:
/// <summary> /// 图片转换 /// </summary> /// <param name="strPath"></param> /// <returns></returns> private byte[] reDyte(string strPath) { byte[] bytes = null; try { FileStream fsMyfile = null; if (Directory.Exists(Server.MapPath(strPath))) { // 以二进制方式读文件 fsMyfile = new FileStream(Server.MapPath(strPath), FileMode.OpenOrCreate, FileAccess.ReadWrite); } else { fsMyfile = new FileStream(Server.MapPath(saveDir + "/default.jpg"), FileMode.OpenOrCreate, FileAccess.ReadWrite); } // 创建一个二进制数据流读入器,和打开的文件关联 BinaryReader brMyfile = new BinaryReader(fsMyfile); // 把文件指针重新定位到文件的开始 brMyfile.BaseStream.Seek(0, SeekOrigin.Begin); bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString())); // 关闭以上new的各个对象 brMyfile.Close(); } catch { // 以二进制方式读文件 FileStream fsMyfile = new FileStream(Server.MapPath(saveDir + "/default.jpg"), FileMode.OpenOrCreate, FileAccess.ReadWrite); // 创建一个二进制数据流读入器,和打开的文件关联 BinaryReader brMyfile = new BinaryReader(fsMyfile); // 把文件指针重新定位到文件的开始 brMyfile.BaseStream.Seek(0, SeekOrigin.Begin); bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString())); // 关闭以上new的各个对象 brMyfile.Close(); } return bytes; }
根据网络路径将图片保存到本地
/// <summary> /// 保存url图片到本地 /// </summary> /// <param name="url"></param> /// <param name="savePath"></param> private string SaveUrlImage(string url) { string savePath = ""; try { HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse(); if (webresponse.StatusCode == HttpStatusCode.OK) { System.Drawing.Image image = System.Drawing.Image.FromStream(webresponse.GetResponseStream()); savePath = saveDir + "/" + DateTime.Now.ToString("yyyyMMddHHmmssfffff") + ".jpg"; image.Save(Server.MapPath(savePath)); //保存在本地文件夹 image.Dispose(); //释放资源 } } catch { } return savePath; }
将二进制格式图片保存到本地
System.IO.MemoryStream ms = new System.IO.MemoryStream(imgData); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); img.Save(savePath);
检查文件是否存在
Directory.Exists(severDir)
参考资料:http://developer.51cto.com/art/200908/143612.htm
http://www.oschina.net/code/snippet_222150_15091
标签:
原文地址:http://www.cnblogs.com/Jokers/p/4425085.html