2009年9月10日 星期四

Get Image form Web by C#

以下範例 簡單的說明c# 取得位在網路上圖片的方法, 並將圖片暫存成 BitmapImage


ImgSource 為一個url string 如 "http://lh3.ggpht.com/_aUxwb_torSg/SZ5FjN1UkzI/AAAAAAAAAds/0FM7vPHF0Ho/showBorder.png"

Code 如下


public BitmapImage GetImagefromWeb(string ImgSource)
{
/// Declare BitmapImage Bi
BitmapImage Bi = new BitmapImage();

/// Create the requests.
WebRequest requestPic = WebRequest.Create(ImgSource);

/// Se proxy
/// if web request by proxy
IWebProxy iProxy = WebRequest.DefaultWebProxy;

/// Get potentially, setup credentials on the proxy here
iProxy.Credentials = CredentialCache.DefaultCredentials;

/// Set proxy
requestPic.Proxy = iProxy;


/// Get response
WebResponse responsePic = requestPic.GetResponse();



Bi.BeginInit();

/// Set Bi source from Stream
Bi.StreamSource = responsePic.GetResponseStream();

Bi.EndInit();



return Bi;

}

沒有留言: