Search code examples
phpimagemagickimagick

Imagick setColor not working with php


I've tried setting all pixels to black. But it isn't working. I am getting the same image as original.

Here is my code:

$image = new Imagick(__DIR__."/image_new.jpg");

$i=0;
$j=0;

while ($i < 100)
{
    $j=0;
    while($j < 100)
    {
         $pixel = $image->getImagePixelColor($i, $j); 
         $pixel->setColor("#000000");
         $j++;
    }

    $i++;
}

header("content-type:image/jpeg");
echo $image;

Image size is 100x100.

Any ideas?


Solution

  • The Imagick::getImagePixelColor will return an ImagickPixel object; which, would have copied data from the originating Imagick object. After altering the pixel's data/state, you would need to "sync" the pixel back to the image. To help with this process, a ImagickPixelIterator object has been provided -- see Imagick::getPixelIterator. Here's a quick example

    $image = new Imagick(__DIR__."/image_new.jpg");
    $pixel_iterator = $image->getPixelIterator();
    foreach($pixel_iterator as $i => $pixels)
    {
     if( $i < 100 )
     {
      foreach($pixels as $j => $pixel)
      {
       if( $j < 100 )
       {
        $pixel->setColor("#000000");
       }
      }
     }
     $pixel_iterator->syncIterator();
    }
    
    header("content-type:image/jpeg");
    echo $image;