Detecting URL of an image in C # /. NET

Is there any way to detect the image URL, for example:

http://mysite.com/image.jpg 

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

Sort of

 bool isImageUrl(string URL){ } 

edit I meant if the url points to an image. For example, URL

 http://mysite.com/image.jpg 

there is a valid image but

 http://mysite.com/image 

not.

+6
source share
4 answers

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

+6
source

You can define it using the HEAD Http method (without loading 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/"); } } 
+10
source

Of course, you can simply check if the URL ends with a known image file extension. However, a safer method is to actually download the resource and check if the content you receive is really 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)) { // eg 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; } 
+3
source

You can simply check the string with .EndsWith () for each of the set of strings you define.

If you want to find out if the object at this URL is really an image, you will need to execute the web request yourself and check the HTTP header of the content.

However, this may be inaccurate, depending on the server.

+1
source

Source: https://habr.com/ru/post/918355/


All Articles