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.
- /* Create new object with the image */
- $im = new Imagick( "strawberry.png" );
- /* Get iterator */
- $it = $im->getPixelIterator();
- /* Loop trough pixel rows */
- foreach( $it as $row => $pixels )
- /* For every second row */
- if ( $row % 2 )
- /* Loop trough the pixels in the row (columns) */
- foreach ( $pixels as $column => $pixel )
- /* Paint every second pixel black*/
- if ( $column % 2 )
- $pixel->setColor( "black" );
- /* Sync the iterator, this is important
- to do on each iteration */
- /* Display the image */
- header( "Content-Type: image/png" );
- echo $im;
The source image:
The result image: