0

I am writing a program to retrieve an image from an existing url. This is my function.

public static Image GetImageFromURL(string url)
{
    try
    {
        WebClient client = new WebClient();
        if (url.Contains("url("))
        {
            url = url.Replace("url(\"", "");
            url = url.Replace("\")", "");
        }
        var tmp = client.DownloadData(url);

        return Image.FromStream(new MemoryStream(tmp));
    }
    catch (Exception e)
    {
        return null;
    }
}

Normally this function works with all images, regardless of file extensions. In most cases, the value of "tmp" variable is at around 100000 or 200000 bytes. However there is a case that the image (after parsed to byte array) contains 635 bytes. This resulted in System.ArgumentException was thrown. The exception message is "Parameter is not valid". It happened when Image.FromStream was called.

Has anyone faced similar problems like this? Can you please advise me what should I do? Thanks.

Anthony

  • 1
    Did you break when you hit the Exception and inspected the URL? Anything suspiciously weird in the URL? The image that it points to? Did you check what `tmp` actually contains? 600 bytes sounds suspiciously like text data containing an error message from the server. Try [converting the byte array into string](https://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string). – NPras Oct 12 '17 at 03:37
  • Yes I did try the image url on Chrome and it is perfectly fine. I don't know why after parsing to byte array, it appears very weird like that. – anthony_netdev_2016 Oct 12 '17 at 03:58
  • Maybe the downloaded data is not a valid image, because of some other response of the server. A reason for this might be that the server is too busy ore something else. – scher Oct 12 '17 at 05:18

0 Answers0