0

I'm working on a script that has to work on a large set of images and I need a graceful way to handle corrupt/truncated images in the set.

Currently my script works for all valid images but crashes when it runs into a truncated file. It must've sneaked into the folders but I want to handle this case nevertheless.

Its a *.png.tmp file and when feeding it to imagecreatefrompng(), it causes a fatal error and stops my script.

Fatal error: imagecreatefrompng(): gd-png: fatal libpng error: Read Error: truncated data...

It is recognized as PNG by both getimagesize() and exif_imagetype().

Since I can't handle it as an exception, is there a way to check if the file is valid without crashing my script and without relying on extensions in the filename?

I can live with skipping the image, but I don't know how to recognize it as a problem image before hitting the fatal error.

CptAJ
  • 1,156
  • 1
  • 13
  • 20

1 Answers1

1

Did you try to suppress error by using @ operator, and check if image is actually created?

foreach ($imagePaths as $imagePath)
{
    $image = @imagecreatefrompng($imagePath);
    if (!$image)
    {
        //maybe delete bad image?
        unlink($imagePath);
        continue;//do nothing in this iteration anymore
    }
    //do your magic here
}
Nemanja K.
  • 131
  • 6