Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting image URL in C#/.NET

Tags:

c#

.net

url

c#-4.0

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.

like image 775
svbnet Avatar asked Jun 18 '12 12:06

svbnet


4 Answers

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/");
    }
}
like image 184
L.B Avatar answered Oct 24 '22 00:10

L.B


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

like image 8
SLaks Avatar answered Oct 24 '22 00:10

SLaks


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;
}
like image 3
Dirk Vollmar Avatar answered Oct 24 '22 00:10

Dirk Vollmar


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.

like image 2
dodexahedron Avatar answered Oct 24 '22 00:10

dodexahedron