How to generate thumbnails on the fly with PHP Imagick

We’ve all been in a position where we need to dynamically generate thumbnails from a larger sized images. In order to save myself the annoyance of doing so every time, I’ve made this reusable script which you place directly in the src tag of the image, and it dynamically resizes the image for you. This is a CPU intensive task, so if you run a hot website with a lot of hits either make up some caching mechanism or go for a different solution.

Why use Imagick library instead of the built-in GD to generate thumbnails with PHP

I chose the imagick library, because in my tests it utilizes memory much better than the built-in GD. I`m planning on including a fallback to GD in the next part of this article. But I surely wouldn`t use it for manipulating big images.

The script usage is pretty simple. You use it in the source of the image html element and provide the following GET parameters:

  • mwidth – Max width of the resized image
  • mheight – Max height of the resized image
  • url – The url path to the source image
<img src="http://yoursite.com/thumbnail.php?url=http://yoursite.com/images/image.jpg&mwidth=200&mheight=200" alt="" width="200" height="200" />

The code:

<?php
$url = $_GET['url'];
$maxWidth = $_GET['mwidth'];
$maxHeight = $_GET['mheight'];
$tmpExt = end(explode('/', $url));
$tmpExt = end(explode('/', $url));
$image = @file_get_contents($url);
if($image) {
    $im = new Imagick();
    $im->readImageBlob($image);
    $im->setImageFormat("png24");
    $geo = $im->getImageGeometry();
    $width=$geo['width'];
    $height=$geo['height'];
    if($width > $height)
    {
        $scale = ($width > $maxWidth) ? $maxWidth/$width : 1;
    }
    else
    {
        $scale = ($height > $maxHeight) ? $maxHeight/$height : 1;
    }
    $newWidth = $scale*$width;
    $newHeight = $scale*$height;
    $im->setImageCompressionQuality(85);
    $im->resizeImage($newWidth,$newHeight,Imagick::FILTER_LANCZOS,1.1);
    header("Content-type: image/png");
    echo $im;
    $im->clear();
    $im->destroy();
}

?>

Installation:

There is no installation per say, you just upload the script to your server.

Requirements:

You can download the code for this how-to in
About Pavel Petrov 2 Articles |  21 How-tos
Pavel is a senior developer for the last 7 years, with extended interest in Linux administration, WordPress and Symfony.