How to know if imagick throws an error - PHP

sanchitkhanna26 picture sanchitkhanna26 · Apr 8, 2013 · Viewed 8.5k times · Source

I am currently using imagick for image processing on my webssite. I have it correctly installed and is working great. Heres my starting code -:

$image = new imagick($filename); $geo=$image->getImageGeometry();  
$image->setImageInterlaceScheme(2);  $image->setImageCompressionQuality(85);
$image->setImageBackgroundColor('white'); $image = $image->flattenImages(); 
$image->setImageFormat('jpg');   $image->stripImage();

After this i do the rest of the part. Now suppose it throws an error, how do i code for that. I tried adding if(!$image){ echo 'error' exit(); } after $image = new imagick($filename) but in vain.

Please help... Thanks all :)

Answer

user1909426 picture user1909426 · Apr 8, 2013

If an error occurs, Imagick will throw an ImagickException which you can catch:

    try {
        $image = new Imagick($filename);
        $geo = $image->getImageGeometry();  
        $image->setImageInterlaceScheme(2);  
        $image->setImageCompressionQuality(85);
        $image->setImageBackgroundColor('white'); 
        $image = $image->flattenImages(); 
        $image->setImageFormat('jpg');   
        $image->stripImage();
    } catch (ImagickException $e) 
{
        var_dump($e);
    }

for further reference see here.