在Winforms應用程序中,我有一個登錄到網站的webbrowser控件。 現在我想以編程方式下載一張圖片(只能在登錄到該網站時下載)。c#winforms網頁瀏覽器控制 - 如何下載圖像?
那麼如何告訴我的瀏覽器控件下載圖像,即。 http://www.example.com/image.jpg,並保存在某個地方?
在Winforms應用程序中,我有一個登錄到網站的webbrowser控件。 現在我想以編程方式下載一張圖片(只能在登錄到該網站時下載)。c#winforms網頁瀏覽器控制 - 如何下載圖像?
那麼如何告訴我的瀏覽器控件下載圖像,即。 http://www.example.com/image.jpg,並保存在某個地方?
如果您不想將文件直接保存到硬盤驅動器,可以將其下載到流中。例如
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData("http://www.example.com/image.jpg");
Bitmap b = new Bitmap(new MemoryStream(bytes));
如果再希望將它保存到你的硬盤,你可以調用Bitmap.Save()
方法。例如
b.Save("bitmap.jpg");
我想你不能用WebBrowser靜靜地做到這一點。不要忘記,它最終是一個IE實例。你可以做的是:導航到IMAGEURL,然後調用ShowSaveAsDialog(),將顯示一個另存爲對話框,用戶保存的圖片:
WebBrowser wb = new WebBrowseR();
wb.Navigate("ImageURL");
wb.ShowSaveAsDialog();
更好的解決方案是使用Web客戶端
來獲得圖像System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("username", "password"); //Authenticates to the website - Call it only if the image url needs authentication first
wc.DownloadFile("imageURL", "downloadedImage.jpg"); //Downloads the imageURL to the local file downloadedImage.jpg