.NET:验证URL是图像

时间:2009-09-20 07:33:28

标签: image url verify

我需要验证用户指定的URL是否适用于图像。所以我真的需要一种方法来确定URL字符串指向有效的图像。我怎么能在.NET中做到这一点?

3 个答案:

答案 0 :(得分:3)

如果不下载文件(至少是其中的一部分),则无法做到这一点。使用WebClient获取网址,然后尝试从返回的Bitmap创建新的byte[]。如果它成功了,它真的是一个形象。否则,它将在进程中的某处抛出异常。

顺便说一句,您可以发出HEAD请求并检查响应中的Content-Type标头(如果有的话)。但是,这种方法并非万无一失。服务器可以使用无效的Content-Type标头进行响应。

答案 1 :(得分:2)

我会使用HttpWebRequest获取标题,然后检查内容类型,并且内容长度不为零。

答案 2 :(得分:0)

这是我现在正在使用的内容。任何批评?

public class Image
{
    public static bool Verifies(string url)
    {
        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

        Uri address;

        if (!Uri.TryCreate(url, UriKind.Absolute, out address))
        {
            return false;
        }

        using (var downloader = new WebClient())
        {
            try
            {
                var image = new Bitmap(downloader.OpenRead(address));
            }
            catch (Exception ex)
            {
                if (// Couldn't download data
                    ex is WebException ||
                    // Data is not an image
                    ex is ArgumentException)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }
        }

        return true;
    }
}