使用ImageMagick更改特定位置的像素颜色值

使用ImageMagick更改特定位置的像素颜色值

问题描述:

I have a script like this:

// Loop over image
$size = $im->getImageGeometry(); 
$w = $size['width']; 
$h = $size['height']; 

for ($i=0; $i<$w; $i++) {
    for ($j=0; $j<$h; $j++) {
        $pixel = $im->getImagePixelColor($j,$i);
        $color = $pixel->getColor();
        $pixel->setColor("rgb(0,0,255)");     
    }
}

Preferably I'd like the setColor command to change the color of the pixel at the specified (x,y) location, so that when I call something like:

echo '<img src="data:image/jpg;base64,'.base64_encode($im->getImageBlob()).'" alt="" />';

An updated image will show. However, this does not work since I guess the $pixel was returned by value instead of by reference. It would actually be preferable if there was a getImagePixelColor method but I can't seem to find anything on it.

Does anyone know of a way to do this with imagemagick, or maybe recommend a library in php that can do this easily?

See this question, "Imagick setColor not working with php". You'll need to initialize a pixel iterator to access a specific pixel, and sync any color changes back to the image.

$image = new Imagick("someimage.png");
$pixel_iterator = $image->getPixelIterator();
foreach($pixel_iterator as $y => $pixels)
{
  foreach($pixels as $x => $pixel)
  {
   $pixel->setColor("rgb(0,0,255)");
  }
 $pixel_iterator->syncIterator();
}