c# - 从 HTML 源下载并保存图像

标签 c# asp.net

在我们的应用程序中,基于一些输入数据,将渲染图像。图片是一些图表。作为我们测试自动化的一部分,我需要下载这些图表。

我只有图片源网址。如何从源下载图像并将其保存到磁盘。

我尝试使用不同的方法并能够下载文件。但是当我尝试打开该文件时,收到一条消息说“不是有效的位图文件,或其格式目前不受支持。”

这是我的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> 

最佳答案

找到了答案。我们必须根据您的要求从网站设置 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();
        }
    }
}

关于c# - 从 HTML 源下载并保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014189/

相关文章:

asp.net - 何时在 sql 2008 中使用时间戳?

c# - 如何使用 API 在 ASP C# 中实现 POST 和上传文件?

asp.net - 标识列增量跳转

c# - 如何在 5 秒后更改字符串值?

c# - Linq 和 SQL 之间的不同结果

c# - 具有许多注释表的多对象

C# - 在程序运行时重写/编辑行

c# - 如何定义显示的数据?

html - 在 Visual Studio 2019 中使用的 Razor View 未更新

asp.net - 需要将用户限制为单个浏览器 session