如何检查是否一个字节数组是一个有效的图像?是一个、数组、字节、图像

2023-09-07 12:21:38 作者:别来无恙

我知道有没有净功能存在检查,但有一个算法或检查,如果一个字节是一个有效的图像之前,我使用的字节数组的简单有效的方法。予需要这种因为我送不同的命令到服务器谁是不断聆听客户端和命令之一是让服务器的计算机的屏幕截图。

I know there is no .Net function that exists for checking, but is there an algorithm or easy and effective way of checking if a byte is a valid image before I use the byte array. I need this because I'm sending different commands to a server who is constantly listening to the client and one of the commands is to get the screenshot of the server's computer.

推荐答案

您可以尝试生成的字节数组中的图像,如果它不检查的ArgumentException

You can try to generate an image from the byte array and check for the ArgumentException if its not.

public static bool IsValidImage(byte[] bytes)
{
    try {
        using(MemoryStream ms = new MemoryStream(bytes))
           Image.FromStream(ms);
    }
    catch (ArgumentException) {
       return false;
    }
    return true; 
}