2009年9月11日 星期五

轉貼 從網路取得圖片 儲存 成 Byte[] by C #

資料來源

http://bytes.com/topic/c-sharp/answers/235707-save-image-url


這裡有用到 BinaryReader. ReadBytes(count )的 function 可以參考MSDN的說明

http://msdn.microsoft.com/zh-tw/library/system.io.binaryreader.readbytes%28VS.80%29.aspx


其中 count 表示要讀取的位元組數目, 此範例 設 500000,
實際圖片轉換成byte[]必須比這個數目小,否則會lose 資料,
儲存完成 範例的 byte[] b 會依據實際的大小作調整

Code 如下




static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}




還有將byte[] 儲存成image 的函式




static public void WriteBytesToFile(string fileName, byte[] content)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write(content);
}
finally
{
fs.Close();
w.Close();
}

}


沒有留言: