0

I have to check whether an image is jpg or png (or none of them) and return the format. I have an "ID" of a picture, which I have to look up online and guess the format.

I have two cases:

mydomain.com/ID.jpg
mydomain.com/ID.png

If none work, then return "error" or "unknown type", otherwise return the type of the image.

I tried various methods, but I can't get it working, for some reason I get exceptions.

First, I tried this, but I was getting web exception.

using (WebClient wc = new WebClient())
    {
        try
        {
            if (wc.DownloadString(mydomain.com/ID.png).Contains("PNG"))
            {
                wc.DownloadFile(url, filepath);
            }
            else
            {
                wc.DownloadFile(url, filepath);
            }
        }
        catch (WebException ex)
        {
            if (ex.Response != null && ex.Status == WebExceptionStatus.ProtocolError)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.NotFound)
                {
                    continue;
                }
            }

            throw;
        }
    }

Then I tried a function to check if an URL is an image, and call it

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

Calling it like this:

try
        {
            if (IsImageUrl("mydomain.com/ID.jpg"))
            {
                MessageBox.Show("jpg");
            }
            else
            {
                MessageBox.Show("png");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("other format or error");
        }

I also tried this:

try
            {
                HttpWebRequest request = HttpWebRequest.Create("mydomain.com/ID.jpg") as HttpWebRequest;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                string contentType = "";

                if (response != null)
                    contentType = response.ContentType;

                MessageBox.Show(contentType);
            }
            catch (WebException ex)
            {
                if (ex.Response != null && ex.Status == WebExceptionStatus.ProtocolError)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        //continue;
                    }
                }

                throw;
            }

But I still have the same problem, it throws an exception instead of return it..

So, my question is: Given the situation in the beginning of post, I need to check two URLs, by adding .jpg and .png at the end of each, whether one of them is valid, if so, return which (the format), otherwise return "unknown format".

user5204184
  • 341
  • 6
  • 15
  • 2
    `it throws an exception instead` Does this exception have a message? stacktrace? – Eser Sep 03 '15 at 07:41
  • @Eser Yes, it's "Forbidden" 403. – user5204184 Sep 03 '15 at 07:42
  • 1
    aren't your `if and else` condition doing the same thing.please take a look at your first code snippet – Rohit Sep 03 '15 at 07:43
  • See this link if it helps you get rid of the exception http://stackoverflow.com/questions/3272067/webclient-403-forbidden – Megha Sep 03 '15 at 07:44
  • @kyle What do you mean? – user5204184 Sep 03 '15 at 07:44
  • @Meghaa The exception happens because the image on that URL doesn't exist and the website returns 403. – user5204184 Sep 03 '15 at 07:45
  • I think what kyle means is that irrespective of whether its png or not, you still download the file – Megha Sep 03 '15 at 07:47
  • @Meghaa In my first snippet code, it downloads only .png files, and throws a 403 for .jpg ones – user5204184 Sep 03 '15 at 07:48
  • Independently upon the exact reason for your problem, note that you can check the format of the image (jpg or png) without caring about the given extension (i.e., a png file renamed as image.jpg would be recognised as png); at least, if you have full access to it (= associated with an Image/Bitmap variable). The kind of remote check you are doing is most likely limited to just look at the extension. – varocarbas Sep 03 '15 at 07:56
  • @varocarbas Thanks for the information, I think I understand that. However in my case I have to check both links regardless. If it was only one link I had to check, It probably would be easier, but since there are two, I don't know which one is the working one. – user5204184 Sep 03 '15 at 08:00
  • But why not downloading the file(s) as any file (regardless of being an image) and checking the format locally? – varocarbas Sep 03 '15 at 08:03
  • @varocarbas Isn't it the same? Because I will have to check if the URL exists or not, regardless. – user5204184 Sep 03 '15 at 08:06
  • A good way to fix a problem is reducing the situation to its simplest version to make it work and then keep adding layers of complexity. In this case, you are not sure if the file does not exist; if it exist but the format is different; if the image-based approach you are using is not OK; if the server has a problem dealing with your request... Go simple. Check all the files in the given directory, download them and confirm that this part works fine (then do tests on images, then...). If you cannot even download a single file, you shouldn't worry about the image formats anyway. – varocarbas Sep 03 '15 at 08:10
  • @varocarbas The problem is that I do not have access to the directory. I have to do it by IDs. I only have the list of IDs, but not access to directory. So I have to send requests to ID.jpg and ID.png and check which one actually exists. – user5204184 Sep 03 '15 at 08:16
  • I know (I have read your question). And this is a pretty straightforward situation where you have to check if the given file exists. But you are saying that you are getting errors anyway, by forgetting that the problem is in your specific conditions (not in the general way to face this situation). I have proposed a step-by-step approach to help you understand how to deal with it. I think that I have already spent enough time here (+ you have quite a few other comments + what should be done is quite clear), so I will better stop the conversation here. – varocarbas Sep 03 '15 at 08:20
  • @varocarbas Thank you for your time and help, but I already tried to check if it exists, or not. I used DownloadString() for example, but the problem is that when 403 occurs, it throws the exception immediately. I tried handling it with `continue` in the first code, but it didn't work out. The exception kept happening and it would only download .png files, but not the .jpg ones. – user5204184 Sep 03 '15 at 08:24
  • Do make sure not to get tripped by case: Some servers are case-insensitive but many are in fact not. Checking for 'PNG' or 'png' will make a difference then!! – TaW Sep 03 '15 at 11:21

0 Answers0