如何检查字节数组是否为有效图像? [英] How to check if a byte array is a valid image?

查看:22
本文介绍了如何检查字节数组是否为有效图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道没有用于检查的 .Net 函数,但是在我使用字节数组之前,是否有算法或简单有效的方法来检查字节是否为有效图像.我需要这个,因为我正在向不断监听客户端的服务器发送不同的命令,其中一个命令是获取服务器计算机的屏幕截图.

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; 
}

这篇关于如何检查字节数组是否为有效图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆