【问题标题】:Create image only when url returns image type仅当 url 返回图像类型时创建图像
【发布时间】:2016-01-04 05:52:53
【问题描述】:

我正在尝试从 url 获取图像。如果该 url 中不存在图像,则该 url 返回一个静态 html 页面。

这是我用来创建图像的代码

img_profile.ImageSource = new BitmapImage(new Uri("www.someurl.com/xyz.jpg"));

img_profile 是我的图像控件 ID。

如果url返回静态html页面,那么我想显示静态图像。

我正在创建 Windows 通用应用程序。

【问题讨论】:

  • 尝试使用字符串解析,您可以根据需要从字符串中获取内容。

标签: c# windows-phone-8.1 winrt-xaml


【解决方案1】:

您可以使用ContentType 来检查它是图像还是静态 html 内容。

创建一个检查 ContentType 的方法。

public static bool IsValidImage(string url)
       {
           var request = (HttpWebRequest)HttpWebRequest.Create(url);
           request.Method = "HEAD";
           using (var response = request.GetResponseAsync().Result)
           {
               return response.ContentType.ToLower().StartsWith("image/");

           }
       }

如果此方法返回 false,则您可以显示默认图像。

【讨论】:

  • 谢谢阿米特。这有帮助。
【解决方案2】:

试试下面的代码。

你的代码

string url = @"www.someurl.com/xyz.jpg";
if (IsImageUrl(url))
    img_profile.ImageSource = new BitmapImage(new Uri(url));
else
    img_profile.ImageSource = new BitmapImage(new Uri("default_image.jpg"));

创建可以检查 url 的函数是否用于图像?

using System.Net;
using System.Globalization;

bool IsImageUrl(string URL)
{
    var req = (HttpWebRequest)HttpWebRequest.Create(URL);
    req.Method = "HEAD";
    using (var resp = req.GetResponse())
    {
        return resp.ContentType.ToLower(CultureInfo.InvariantCulture)
                   .StartsWith("image/");
    }
}

看到这个问题Detecting image URL in C#/.NET

【讨论】:

  • 感谢 Darshan 的回复,但 req.GetResponse 在 Windows 通用应用程序中不起作用。它有 GetresponseAsync 选项,但同样 resp.ContentType 不起作用。
【解决方案3】:
**BitmapImage bmp = new BitmapImage(new Uri("www.someurl.com/xyz.jpg"));
if(File.Exists("www.someurl.com/xyz.jpg"))    
{   
            img_profile.ImageSource=bmp;   
}  
else  
{      
           img_profile.ImageSource= new BitmapImage(new Uri("Static image path"));  
}  
I hope it will work...**

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2019-10-23
    • 2022-08-12
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 2012-09-02
    相关资源
    最近更新 更多