9

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

  • What image formats do you need to support? If its just the basic 4 (bmp/png/gif/jpg) you could use the bitmap class and just attempt loading them. – Will Jan 13 '12 at 06:19
  • possible duplicate of [How Do I Validate a JPEG Image in C# / .Net is not corrupted](http://stackoverflow.com/questions/1173349/how-do-i-validate-a-jpeg-image-in-c-sharp-net-is-not-corrupted) – V4Vendetta Jan 13 '12 at 06:21
  • The Bitmap class can take bytes. Do you want to just check if its an image or do you want to check if its an image and a valid image? – Will Jan 13 '12 at 06:27

2 Answers2

15

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;
    }
}
rsbarro
  • 27,021
  • 9
  • 71
  • 75
  • OK. fine looks that is just what I needed! Thanks. –  Jan 13 '12 at 06:27
  • This should be used with care. It's important that you release the Bitmap created with *using*. Else it is quite possible that you'd get OutOfMemory Exception while checking large number of files because the system ran out of resources and not because image is corrupt. – Indy9000 Apr 22 '15 at 11:57
  • 1
    @Kip9000 When the code within the using statement is complete, the bitmap will be disposed. No need to explicitly dispose of it. – rsbarro Apr 22 '15 at 14:14
  • 1
    See here for more info on using statements: https://msdn.microsoft.com/en-us/library/yh598w02.aspx – rsbarro Apr 22 '15 at 15:05
  • I was emphasizing that using 'using' is important. Your code is correct – Indy9000 Apr 22 '15 at 15:49
0

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.

Community
  • 1
  • 1
Lost_In_Library
  • 3,265
  • 6
  • 38
  • 70