I work for Norway’s largest web site and on our site we have a daily Dilbert comic. We receive these comics in large TIFF files and we have previously done some manual work to generate a nice preview and a scaled version of the comic. Manual work sucks so I have written a small PHP script that uses ImageMagick (using the imagick extension) to do all the work for us. The imagick part of the script looks something like:
// Open a new image $image = new Imagick($filepath); // $filepath is a path to a TIFF file // Scale the image $image->resizeImage(600, 189, imagick::FILTER_LANCZOS, 1); // Store the scaled version $image->writeImage($outputDir . '/' . $outputFilename); // generate a thumb that includes the first tile of the comic $image->cropImage(194, 188, 0, 0); // Scale the thumb $image->resizeImage(115, 111, imagick::FILTER_LANCZOS, 1); // Store the thumb $image->writeImage($outputDir . '/' . $outputThumbFilename);
Now … at first glance this should work pretty nice. Well … it doesn’t!
Take a look at the two files that are generated:
As you can see the thumbnail is fubar. Mats happened to figure out that the image actually is 115×111 but the header of the GIF says otherwise. Because of this image viewers (like a browser for instance) will show the image inside the size specified in the header. Sounds like a bug in the crop function in either ImageMagick or the imagick extension.
To fix the problem we need to set the page size before we store the thumb:
// More stuff (see snippet above) // ... // Scale the thumb $image->resizeImage(115, 111, imagick::FILTER_LANCZOS, 1); // Set the page size $image->setImagePage(115, 111, 0, 0); // Store the thumb $image->writeImage($outputDir . '/' . $outputThumbFilename);
The result of this is a correct thumbnail:
Hopefully Scott Adams won’t mind me displaying one of his comics in my blog. If you (Scott Adams) happen to read this, and want them removed, just say the word. :)