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="" alt="" width="200" height="200" alt="Generate thumbnails with php"/>

And here is the code itself:

$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();
    if($width > $height)
        $scale = ($width > $maxWidth) ? $maxWidth/$width : 1;
        $scale = ($height > $maxHeight) ? $maxHeight/$height : 1;
    $newWidth = $scale*$width;
    $newHeight = $scale*$height;
    header("Content-type: image/png");
    echo $im;


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.

One thought on “Generate thumbnails with PHP and Imagick on the fly – Part 1”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>