I know, it’s been a while since I last blogged. This is because a lot of things are happening in my personal life. I recently relocated to London from Finland and started a new job. Things are quite busy but I will try to post an example now and then. In the meanwhile I would like to hear about sites using Imagick, so if your project is not super secret please post an url and maybe a small explanation what you’re doing with Imagick on the site. This is purely for my personal interest.

Anyway, to the point. Today’s example originates from a question asked by a user. How do I thumbnail the image inside given dimensions proportionally and fill the “blank” areas with a color? Well, the answer is here :)

The code is for Imagick 2.1.0 but adapting to older versions should not be hard.

  1. <?php
  2. /* Define width and height of the thumbnail */
  3. $width = 100;
  4. $height = 100;
  5.  
  6. /* Instanciate and read the image in */
  7. $im = new Imagick( "test.png" );
  8.  
  9. /* Fit the image into $width x $height box
  10.  The third parameter fits the image into a "bounding box" */
  11. $im->thumbnailImage( $width, $height, true );
  12.  
  13. /* Create a canvas with the desired color */
  14. $canvas = new Imagick();
  15. $canvas->newImage( $width, $height, 'pink', 'png' );
  16.  
  17. /* Get the image geometry */
  18. $geometry = $im->getImageGeometry();
  19.  
  20. /* The overlay x and y coordinates */
  21. $x = ( $width - $geometry['width'] ) / 2;
  22. $y = ( $height - $geometry['height'] ) / 2;
  23.  
  24. /* Composite on the canvas  */
  25. $canvas->compositeImage( $im, imagick::COMPOSITE_OVER, $x, $y );
  26.  
  27. /* Output the image*/
  28. header( "Content-Type: image/png" );
  29. echo $canvas;
  30.  
  31. ?>

The source image:
test.png

The resulting image:
testphp.png