A few days ago I got a help request from a user: “How do you change pixel color during the iteration with ImagickPixelIterator”. My initial response was that ImagickPixelIterator is read-only.

Well, I have to admit I was wrong. After searching trough ImageMagick docs I stumbled across an example and noticed that PixelIterator (and therefor ImagickPixelIterator) is not read-only after all. I have tried the code like in this example before; without the syncIterator call after each row. After adding the Imagick::syncIterator call everything worked as expected.

This example will work with Imagick 2.1.0 (the RC1 was released yesterday) but with a little tweaking it should work with 2.0.x too.

  1. <?php
  2.  
  3. /* Create new object with the image */
  4. $im = new Imagick( "strawberry.png" );
  5.  
  6. /* Get iterator */
  7. $it = $im->getPixelIterator();
  8.  
  9. /* Loop trough pixel rows */
  10. foreach( $it as $row => $pixels )
  11. {
  12.     /* For every second row */
  13.     if ( $row % 2 )
  14.     {
  15.         /* Loop trough the pixels in the row (columns) */
  16.         foreach ( $pixels as $column => $pixel )
  17.         {
  18.                 /* Paint every second pixel black*/
  19.                 if ( $column % 2 )
  20.                 {
  21.                         $pixel->setColor( "black" );
  22.                 }
  23.         }
  24.     }
  25.    
  26.     /* Sync the iterator, this is important
  27.     to do on each iteration */
  28.     $it->syncIterator();
  29. }
  30.  
  31. /* Display the image */
  32. header( "Content-Type: image/png" );
  33. echo $im;
  34.  
  35. ?>

The source image:

strawberry

The result image:

strawberry_result