Generate thumbnails with PHP and Imagick on the fly – Part 1

I don’t know about you, but I am sick and tired of writing thumbnail generation scripts! I recently worked on a project which where I was required to dynamically generate thumbnails with php (a lot of them and in a variety of sizes). And quite frankly I don`t think I want to go through the whole process of searching the most optimal algorithm for images resize (with minimal quality loses, of course) ever again. So I`ve decided to post a pretty simple, but effective script which will help you to generate thumbnails with php on the fly, using the Imagick PHP library. When I was searching for a good and memory efficient way of resizing and converting images I was overwhelmed by all the different functions and solutions I found, most of which overly complicated.

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.

So the script I wrote is pretty simple you supply the url, max width and max height as get arguments and it returns a generated thumbnail scaled to fit the maximum width and height you provided with maintained aspect ratio.
The usage is pretty simple. In stead of having to go through the whole resize process manually you  embed your thumbnail like this:

<img src="http://yoursite.com/thumbnail.php?url=http://yoursite.com/images/image.jpg&mwidth=200&mheight=200" 
alt="" width="200" height="200" alt="Generate thumbnails with php"/>

And here is the code itself:


<?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();
    //print_r($geo);
    $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();
}

?>

Requirements: The script requires Imagick library.

Installation: Just paste the script somewhere in your site root.

If you need more info about how to generate thumbnails with PHP and Imagick library go and check its docs here.

0  Stars, Based on 0 Reviews

  • http://Antonov-BG.eu Desislav Antonov

    Nice tutorial, it helps me very much!

    Thank! :)