Finally (after a long break) I managed to force myself to update the PHP documentation and this time it was distortImage code example. Things have been hectic lately but that does not quite explain the 6 months(?) break between this and the previous post. As a matter of a fact there is no excuse for such a long silence so I will try to update this blog a bit more often from now on.

Back in the day I used to blog the examples and update the documentation if I remembered but I am trying to fix this bad habit. Most of the latest examples have been updated in to the manual. In the case of the two last examples I updated the documentation first and then blogged on the subject.

I took some time to actually understand the perspective transformations properly using the excellent ImageMagick examples (mainly created by Anthony Thyssen) as a reference. The basic idea of perspective distortion seems simple: to distort the control points to new locations. Grabbing the syntax for Imagick was easy, an array of control point pairs in the form of:

  1. array(source_x, source_y, dest_x, dest_y ... )

The following example uses the built-in checkerboard pattern to demonstrate perspective distortion:

  1. <?php
  2. /* Create new object */
  3. $im = new Imagick();
  4.  
  5. /* Create new checkerboard pattern */
  6. $im->newPseudoImage(100, 100, "pattern:checkerboard");
  7.  
  8. /* Set the image format to png */
  9. $im->setImageFormat('png');
  10.  
  11. /* Fill background area with transparent */
  12. $im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
  13.  
  14. /* Activate matte */
  15. $im->setImageMatte(true);
  16.  
  17. /* Control points for the distortion */
  18. $controlPoints = array( 10, 10,
  19.                         10, 5,
  20.  
  21.                         10, $im->getImageHeight() - 20,
  22.                         10, $im->getImageHeight() - 5,
  23.  
  24.                         $im->getImageWidth() - 10, 10,
  25.                         $im->getImageWidth() - 10, 20,
  26.  
  27.                         $im->getImageWidth() - 10, $im->getImageHeight() - 10,
  28.                         $im->getImageWidth() - 10, $im->getImageHeight() - 30);
  29.  
  30. /* Perform the distortion */  
  31. $im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);
  32.  
  33. /* Ouput the image */  
  34. header("Content-Type: image/png");
  35. echo $im;
  36. ?>

Here is the source image:
checker before

And the result:
after