简体   繁体   中英

Detecting image URL in C#/.NET

Is there a way I can detect an image URL, like:

http://mysite.com/image.jpg

but with other formats as well? I am using C# with .NET 4.0.

Something like

bool isImageUrl(string URL){
}

edit I meant if the URL points to an image. Eg, the URL

http://mysite.com/image.jpg

is a valid image, but

http://mysite.com/image

is not.

You can detemine it using the HEAD method of Http (without downloading the whole image)

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/");
    }
}

You can send an HTTP request to the URL (using HttpWebRequest ), and check whether the returned ContentType starts with image/ .

You could of course simply check whether the URL ends with a known image file extension. However, a safer method is to actually download the resource and check, whether the content you get actually is an image:

public static bool IsUrlImage(string url)
{
    try
    {
        var request = WebRequest.Create(url);
        request.Timeout = 5000;
        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                if (!response.ContentType.Contains("text/html"))
                {
                    using (var br = new BinaryReader(responseStream))
                    {
                        // e.g. test for a JPEG header here
                        var soi = br.ReadUInt16();  // Start of Image (SOI) marker (FFD8)
                        var jfif = br.ReadUInt16(); // JFIF marker (FFE0)
                        return soi == 0xd8ff && jfif == 0xe0ff;
                    }
                }
            }
        }
    }
    catch (WebException ex)
    {
        Trace.WriteLine(ex);
        throw;
    }
    return false;
}

You could just check the string with .EndsWith() for each of a set of strings you define.

If you want to know if the object at that URL is actually an image, you will have to perform the web request yourself and check the content-type HTTP header.

Even that may be inaccurate, however, depending on the server.

An option would be to use HttpClient from System.Net.Http rather than

HttpClient client = new HttpClient();

HttpResponseMessage res = await client.GetAsync("https://picsum.photos/200/300");

bool IsTypeImage = res.ToString().Contains("Content-Type: image");

You can send a HEAD type request using HttpClient which will allow you to make a conclusion on whether it's an image without having to download the whole thing.

Example

bool IsImageUrl(string url)
{
    using var client = new HttpClient();
    var response = client.Send(new HttpRequestMessage(HttpMethod.Head, url));
    return response.Content.Headers.ContentType.MediaType
        .StartsWith("image/", StringComparison.OrdinalIgnoreCase);
}

Extra info

I based the solution on @LB 's answer . Consider this as an alternative for .NET 6+, since after that version, the WebRequest class is considered obsolete (Source: Microsoft documentation )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM