Search code examples
c#itextabstract-classsystem.drawing.imaging

Detect a corrupt image file


Hi All you clever guys,

Im faceing a bit of a challenge here. Im supposed to create several different PDF's containing multiple (not similar) images.

Unfortunately some of the images are corrupt/defect. This causes the creation of the partikular PDF to fail/dump.

Is there a way I can test the image prior to creation of the PDF?

Please be gentle with me. Im not an expert.

I found out that System.Drawings.Image can test some formats. Better than nothing I guess (it will reduce the subset significantly).

But when using iTextSharp.text.Image for the creation of the PDF's. Then I dont know how to use the System.Drawings.Image because when I try Image newImage = Image.FromFile("SampImag.jpg"); then it (Image) refers to the iTextSharp.text.Image class.

System.Drawings.Image is abstract, so I've tried to create a subclass.

public class ImageTest : System.Drawing.Image
    {

    }

Now I get the error message:"Error 1 The type 'System.Drawing.Image' has no constructors defined" Trying to investigate which constructors I can use gives me this attempt.

public class ImageTest : System.Drawing.Image
    {
      ImageTest(string filename);
      {
      }
    }

But this doesn't work.

Please inform me if there is information you need which is relevant to you for investigating this matter.

Thanks in advance.


Solution

  • You should just be able to use

    public bool IsValidImageFile (string imageFile)
    {
        try
        {
            // the using is important to avoid stressing the garbage collector
            using (var test = System.Drawing.Image.FromFile(imageFile))
            {
                 // image has loaded and so is fine
                 return true;
            }
        }
        catch
        {
            // technically some exceptions may not indicate a corrupt image, but this is unlikely to be an issue
            return false;
        } 
    }