/// <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; }
根據網絡路徑將圖片保存到本地web
/// <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);
檢查文件是否存在ide
Directory.Exists(severDir)
參考資料:http://developer.51cto.com/art/200908/143612.htmurl
http://www.oschina.net/code/snippet_222150_15091spa