Reputation: 153
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.
Upvotes: 1
Views: 2470
Reputation:
Catch OutOfMemoryException works:
try
{
// Using System.Drawing.Image
System.Drawing.Image img = (System.Drawing.Bitmap)System.Drawing.Image.FromFile("myimage.png");
}
catch (OutOfMemoryException ex)
{
// Handle the exception...
}
I tested it with this code:
try
{
System.Drawing.Image img = (System.Drawing.Bitmap)System.Drawing.Image.FromFile("myimage.png");
}
catch (OutOfMemoryException ex)
{
Console.WriteLine("Error loading image...");
}
And I deleted a few characters in a .png
file, and the console said:
Error loading image...
And to convert it into a iTextSharp.text.Image
Upvotes: 1
Reputation: 1138
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;
}
}
Upvotes: 3