Read image and determine if its corrupt C#

2019-04-07 22:50发布

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#?

Thanks

标签: c# image corrupt
2条回答
Evening l夕情丶
2楼-- · 2019-04-07 23:20

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

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;
    }
}
查看更多
在下西门庆
3楼-- · 2019-04-07 23:34

You can look these links for taking an idea. First one is here; Validate Images

And second one is here; How to check corrupt TIFF images

And sorry, I don't know any external library for this.

查看更多
登录 后发表回答