2012-06-13 56 views
2

在我們的應用程序中,基於一些輸入數據,圖像將被渲染。圖像是一些圖表。作爲我們測試自動化的一部分,我需要下載這些圖表。從HTML源文件下載並保存圖像

我只是有圖片源的網址。我如何從源下載圖像並將其保存到磁盤。

我試過使用不同的方法並能夠下載文件。但是,當我嘗試打開文件時,收到一條消息,指出'不是有效的位圖文件,或其格式目前不受支持。'

這裏是我的html

<div id="chart"> 
    <img id="c_12" src="Bonus/ModelChartImage?keys%5B0%5D=UKIrelandEBIT&values%5B0%5D=100&privacyModeServer=False&modelId=Bonus" alt="" usemap="#c_12ImageMap" style="height:300px;width:450px;border-width:0px;" /> 
<map name="c_12ImageMap" id="c_12ImageMap"> 

    <area shape="rect" coords="255,265,357,266" class="area-map-section" share="Core Bonus" alt="" /> 
    <area shape="rect" coords="128,43,229,265" class="area-map-section" share="Core Bonus" alt="" /> 
</map>  
</div> 
+3

可能重複:http://stackoverflow.com/questions/932390/how-do-i-save-an-image-from-an-url?rq=1 – aquinas

回答

3

找到答案。我們必須根據您的請求設置來自網站的cookie容器。

public static Stream DownloadImageData(CookieContainer cookies, string siteURL) 
{ 
    HttpWebRequest httpRequest = null; 
    HttpWebResponse httpResponse = null; 

    httpRequest = (HttpWebRequest)WebRequest.Create(siteURL); 

    httpRequest.CookieContainer = cookies; 
    httpRequest.AllowAutoRedirect = true; 

    try 
    { 
     httpResponse = (HttpWebResponse)httpRequest.GetResponse(); 
     if (httpResponse.StatusCode == HttpStatusCode.OK) 
     { 
      var httpContentData = httpResponse.GetResponseStream(); 

      return httpContentData; 
     } 
     return null; 
    } 
    catch (WebException we) 
    { 
     return null; 
    } 
    finally 
    { 
     if (httpResponse != null) 
     { 
      httpResponse.Close(); 
     } 
    } 
} 
3

有很多方法可以從網站上下載圖像(WebClient類,HttpWebRequest的,HttpClient的班,順便說一句其中新HttpClient是最簡單的方法)。

下面是例如用類的HttpClient:

HttpClient httpClient = new HttpClient(); 
Task<Stream> streamAsync = httpClient.GetStreamAsync("http://www.simedarby.com.au/images/SD.Corp.3D.4C.Pos.jpg"); 

Stream result = streamAsync.Result; 
using (Stream fileStream = File.Create("downloaded.jpg")) 
{ 
    result.CopyTo(fileStream); 
} 
+0

我試着用不同的方法和能夠下載該文件。但是,當我嘗試打開文件時,收到一條消息,指出'不是有效的位圖文件,或其格式目前不受支持。' – Naresh

+0

檢查你確實下載了圖像。可能是錯誤的擴展或代替文件HTML內的圖像或因爲「bug」二進制被添加了一些小字符串。所以首先檢查下載的文件。 – Regfor

+0

網站正在處理基於表單的身份驗證。在這種情況下,如果我嘗試從另一個應用程序下載文件,如何將我的請求作爲已認證的請求發送。 – Naresh