HomeImagickImagickDrawImagickPixelImagick Pixel IteratorImagick KernelDevelopmentTutorial Source codeReport an issue
Category
Example

Imagick::setProgressMonitor

← setOption   setSamplingFactors →
Set a callback that will be called during the processing of the Imagick image.
The progress monitor allows you to be notified of progress during image processing. It also allows you to abort the image processing, for example if it's taking too long, or it is detected the image is no longer needed.

In the example below, the progress is monitored and then the image operation is cancelled when the progress passed 20%.

Please note the offset and span values are approximate and do not reflect an accurate measure of the image progress.
ImagickException caught: Unable to wave image Exception type is ImagickException

Example

$output = "<pre>";
$abortReason = null;
try {
    $imagick = new \Imagick(realpath($this->imageControl->getImagePath()));
    $startTime = time();
    $callback = function ($offset, $span) use ($startTime, &$abortReason) {
        if (((100 * $offset) / $span) > 20) {
            $abortReason = "Processing reached 20%";
            return false;
        }
        $nowTime = time();
        if ($nowTime - $startTime > 5) {
            $abortReason = "Image processing took more than 5 seconds";
            return false;
        }
        if (($offset % 5) == 0) {
            $output .= "Progress: $offset / $span <br/>";
        }
        return true;
    };
    $imagick->setProgressMonitor($callback);
    $imagick->waveImage(2, 15);
    $output .= "Data len is: " . strlen($imagick->getImageBlob());
}
catch (\ImagickException $e) {
    if ($abortReason != null) {
        $output .= "Image processing was aborted: " . $abortReason . "<br/>";
    }
    else {
        $output .= "ImagickException caught: " . $e->getMessage() . " Exception type is " . get_class($e);
    }
}