The Wolf The Wolf - 1 month ago 8
PHP Question

Imagine if open() method threw exception ignore then proceed to the next loop

I am trying to use Imagine to batch make 250x250 thumbnail of more than 90k+ relatively small mobile images. The problem is, when I run a loop,

foreach ($images as $c) {
$imagine = new Imagine();
$image = $imagine->open($c);
$image->resize(new Box(250, 250))->save($outFolder);
}


sometimes, the image is corrupted and the
open()
method fails, throwing exception:

Unable to open image
vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php
Line: 96


and completely breaks the loop. Is there a way, to check if
open
failed? something like:

foreach ($images as $c) {
$imagine = new Imagine();
$image = $imagine->open($c);
if ($image) {
$image->resize(new Box(250, 250))->save($outFolder);
} else {
echo 'corrupted: <br />';
}
}


Hope somebody can help. or if its not possible, can you suggest a PHP image library that I can pragmatically resize by batch?

Thank you

Answer

For handling the exception just use try-catch.

From the library documentation

The ImagineInterface::open() method may throw one of the following exceptions:

Imagine\Exception\InvalidArgumentException

Imagine\Exception\RuntimeException

Try it like this:

$imagine = new Imagine(); // Probably no need to instantiate it in every loop
foreach ($images as $c) {
    try {
        $image = $imagine->open($c);
    } catch (\Exception $e) {
        echo 'corrupted: <br />';
        continue;
    }
    $image->resize(new Box(250, 250))->save($outFolder);
}
Comments