仅当 url returns 图像类型时创建图像

Create image only when url returns image type

我正在尝试从 url 中获取图像。如果图像在 url 处不存在,那么 url return 是一个静态 html 页面。

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

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

img_profile是我的图片控件id。

万一urlreturn静态html页面,那么我要显示静态图片。

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

试试下面的代码。

你的代码

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

**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...**

您可以使用 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/");

           }
       }

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