阅读形象,如果腐败的C#确定 [英] Read image and determine if its corrupt C#

查看:107
本文介绍了阅读形象,如果腐败的C#确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定是否我有作为原始字节的图像损坏或不。是否有处理这个问题的多种格式,在C#中的任何开源库?

How do I determine if an image that I have as raw bytes is corrupted or not. Is there any opensource library that handles this issue for multiple formats in C#?

感谢

推荐答案

尝试创建一个GDI +位图从文件。如果创建位图对象失败,那么你可以假定图像已损坏。 GDI +支持多种文件格式:BMP,GIF, ,JPEG,EXIF,PNG,TIFF

Try to create a GDI+ Bitmap from the file. If creating the Bitmap object fails, then you could assume the image is corrupt. GDI+ supports a number of file formats: BMP, GIF, JPEG, Exif, PNG, TIFF.

这样的功能的东西应该工作:

Something like this function should work:

public bool IsValidGDIPlusImage(string filename)
{
    try
    {
        using (var bmp = new Bitmap(filename))
        {
        }
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}

您可能能够限制例外只是的ArgumentException ,但我会首先尝试让交换机之前。

You may be able to limit the Exception to just ArgumentException, but I would experiment with that first before making the switch.

修改

如果你有一个字节[] ,那么这应该工作:

EDIT
If you have a byte[], then this should work:

public bool IsValidGDIPlusImage(byte[] imageData)
{
    try
    {
        using (var ms = new MemoryStream(imageData))
        {
            using (var bmp = new Bitmap(ms))
            {
            }
        }
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

这篇关于阅读形象,如果腐败的C#确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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