c# - 从流中实例化位图时出现 ArgumentException

标签 c# .net c#-4.0

我已经编写了一些代码来从我的 Blogger 博客中导入内容。下载完所有 HTML 内容后,我将浏览图像标签并下载相应的图像。在大量情况下,System.Drawing.Bitmap.FromStream 会抛出 ArgumentException。我从中下载的 URL 看起来不错,并且按预期提供图像(这里是其中一张问题图像的 URL:http://4.bp.blogspot.com/_tSWCyhtOc38/SgIPcctWRZI/AAAAAAAAAGg/2LLnVPxsogI/s1600-h/IMG_3590.jpg)。

    private static System.Drawing.Image DownloadImage(string source)
    {
        System.Drawing.Image image = null;

        // used to fetch content
        var client = new HttpClient();

        // used to store image data
        var memoryStream = new MemoryStream();

        try
        {
            // fetch the image
            var imageStream = client.GetStreamAsync(source).Result;

            // instantiate a system.drawing.image from the data
            image = System.Drawing.Bitmap.FromStream(imageStream, false, false);

            // save the image data to a memory stream
            image.Save(memoryStream, image.RawFormat);
        }
        catch (IOException exception)
        {
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        catch (ArgumentException exception)
        {
            // sometimes, an image will link to a web page, resulting in this exception
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        catch (AggregateException exception)
        {
            // sometimes, an image src will throw a 404
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        finally
        {
            // clean up our disposable resources
            client.Dispose();
            memoryStream.Dispose();
        }

        return image;
    }

知道为什么会在此处抛出 ArgumentException 吗?

编辑:我想到这可能是代理问题,所以我将以下内容添加到我的 web.config 中:

<system.net>
  <defaultProxy enabled="true" useDefaultCredentials="true">
    <proxy usesystemdefault="True" />
  </defaultProxy>
</system.net>

但是,添加该部分没有任何区别。

编辑:此代码是从 EF 数据库初始化程序的上下文中调用的。这是堆栈跟踪:

Web.dll!Web.Models.Initializer.DownloadImage(string source) Line 234 C# Web.dll!Web.Models.Initializer.DownloadImagesForPost.AnonymousMethod__5(HtmlAgilityPack.HtmlNode tag) Line 126 + 0x8 bytes C# [External Code] Web.dll!Web.Models.Initializer.DownloadImagesForPost(Web.Models.Post post) Line 119 + 0x34 bytes C# Web.dll!Web.Models.Initializer.Seed(Web.Models.FarmersMarketContext context) Line 320 + 0xb bytes C# [External Code] App_Web_l2h4tcej.dll!ASP._Page_Views_Home_Index_cshtml.Execute() Line 28 + 0x15 bytes C# [External Code]

最佳答案

好的,我发现了问题。事实证明,在某些情况下,Blogger 引用呈现图像的 HTML 页面而不是引用图像本身。因此,这种情况下的响应不是有效图像。在尝试保存图像数据之前,我添加了代码来检查响应 header ,这解决了问题。为了其他遇到此问题的人的利益,这里是更新后的代码:

    private static System.Drawing.Image DownloadImage(string source)
    {
        System.Drawing.Image image = null;

        // used to fetch content
        var client = new HttpClient();

        // used to store image data
        var memoryStream = new MemoryStream();

        try
        {
            // Blogger tacks on a -h to an image Url to link to an HTML page instead
            if (source.Contains("-h/"))
                source = source.Replace("-h/", "/");

            // fetch the image
            var response = client.GetAsync(source).Result;
            response.EnsureSuccessStatusCode();

            var contentType = response.Content.Headers.ContentType.MediaType;

            if (!contentType.StartsWith("image/"))
            {
                Debug.WriteLine(contentType);
                throw new ArgumentException("Specified source did not return an image");
            }

            var imageStream = response.Content.ReadAsStreamAsync().Result;

            // instantiate a system.drawing.image from the data
            image = System.Drawing.Bitmap.FromStream(imageStream, true, true);

            // save the image data to a memory stream
            image.Save(memoryStream, image.RawFormat);
        }
        catch (HttpRequestException exception)
        {
            // sometimes, we'll get a 404 or other unexpected response
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        catch (IOException exception)
        {
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        catch (ArgumentException exception)
        {
            // sometimes, an image will link to a web page, resulting in this exception
            Debug.WriteLine("{0} {1}", exception.Message, source);
        }
        finally
        {
            // clean up our disposable resources
            client.Dispose();
            memoryStream.Dispose();
        }

        return image;
    }

关于c# - 从流中实例化位图时出现 ArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11415461/

相关文章:

.net - 有什么技巧可以使我的项目每次都以全新的结帐方式进行编译?

c# - 公共(public)内部类

c# - 如何将 System.Reflection.PropertyInfo 对象转换为其原始对象类型

c# - 如何添加xml :lang ="en" to <html> tag

java - 在 C# 中从给定数组中查找平方对

c# - 让 ListView ItemCheck 停止!

.net - 如果将redirectMode设为=“ResponseRewrite”,则不会将错误重定向到Http处理程序

asp.net-mvc-2 - ASP.NET : ActionLink return relative url

c# - 如何使用 C# 中使用 Datahandler 类型的基于 Java 的 SOAP 服务

c# - 线程窗体