Search code examples
c#imagehttpwebrequest

Using C#, how can I detect if an Image URL returns something different from a default image?


I have some code that is using the solution from this question to validate that a certain image url exists.

So I have code that looks like this:

 private bool PictureExists(string id)
    {
        string url = "https://www.example.com/profile.do?userid=" + id;
        var request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "HEAD";

        bool exists;
        try
        {
            request.GetResponse();
            exists = true;
        }
        catch
        {
            exists = false;
        }
        return exists;
    }
}

If a picture didn't exist this function would return false and it worked fine.

The issue now is that the function started returning true and I figured out the root cause is that they have changed the back end to return a default image if what I am searching for doesn't exist.

So my new requirement is how can I check if the image returned is not the default image (so I can replicate the validation that I had before)?


Solution

  • Probably not the best solution, but my first idea was to convert the default image to byte array variable, and then download the image which you want to check, and convert it to byte array. Then you could compare them:

    Code to compare (only from .NET 3.5!):

    static public bool ByteArrayCompare(byte[] a1, byte[] a2) 
    {
        return a1.SequenceEqual(a2);
    }
    

    Code to convert Image to byte[]:

    static public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        return ms.ToArray();
    }
    

    Hope it helps, and sorry for bad english.