Read image and determine if its corrupt C#

半城伤御伤魂 提交于 2019-12-06 01:15:52

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/8846654/read-image-and-determine-if-its-corrupt-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!