简体   繁体   English

使用C#,如何检测图像URL是否返回不同于默认图像的内容?

[英]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. 如果不存在图片,则此函数将返回false并可以正常工作。

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. 现在的问题是该函数开始返回true,而我发现根本原因是,如果我搜索的内容不存在,则它们已更改了后端以返回默认图像。

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)? 因此,我的新要求是如何检查返回的图像是否不是默认图像(以便可以复制以前的验证)?

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!): 要比较的代码(仅适用于.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. 希望对您有所帮助,对不起,英语不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM