Can a PHP imagick iterator modify a separate imagick modifier?

80 views Asked by At

I want to modify 2 imagick objects from the same iterator eg using the docs example

$imagick = new \Imagick(realpath($imagePath));
$imagick2 = clone $imagick;
$imageIterator = new \ImagickPixelIterator($imagick);

/* Loop through pixel rows */
foreach ($imageIterator as $pixels) { 
    /* Loop through the pixels in the row (columns) */
    foreach ($pixels as $column => $pixel) { 
        /** @var $pixel \ImagickPixel */
        if ($column % 2) {
            /* Paint every second pixel black*/
            $pixel->setColor("rgba(0, 0, 0, 0)");
        } else {
            //do something to $imagick2 here 
            $pixel->setColor("rgba(255, 255, 255, 0)");
        }
    }

    /* Sync the iterator, this is important to do on each iteration */
    $imageIterator->syncIterator();

is this possible and what would the syntax look like?

1

There are 1 answers

0
Danack On

The iterators are standard PHP iterators, so the can be iterated through manually using the function next() and current() and checking that it is still valid with valid().

So something like this 'should' work.

$imagick = new \Imagick(realpath($imagePath));
$imagick2 = clone $imagick;
$imageIterator1 = new \ImagickPixelIterator($imagick);
$imageIterator2 = new \ImagickPixelIterator($imagick2);

$imageIterator2->reset(); //make sure iterator is at the start.

/* Loop through pixel rows */
foreach ($imageIterator1 as $pixelRow1) { 

    if (!$imageIterator2->valid()) {
        // need to check validity when iterating manually
        break;
    }

    $pixelRow2 = $imageIterator2->current();
    /* Loop through the pixels in the row (columns) */

    foreach ($pixelRow1 as $column => $pixel1) { 
        /** @var $pixel \ImagickPixel */
        if ($column % 2) {
            /* Paint every second pixel black*/
            $pixel1->setColor("rgba(0, 0, 0, 0)");
        }
        else{
            $pixel2 = $pixelRow2[$column];
            //do something to $imagick2 here 
            $pixel2->setColor("rgba(255, 255, 255, 0)");
        }

        $count++;
    }

    $imageIterator2->next();
    /* Sync the iterator, this is important to do on each iteration */
    $imageIterator1->syncIterator();
    $imageIterator2->syncIterator();
}