How to set color of a pixel using imagick for php (imagemagick)?

99封情书 提交于 2020-01-04 15:33:25

问题


I have get the image pixel of an image at the particular point using getImagePixelColor.

$pixel = $image -> getImagePixelColor($x,$y);

Now I have modified that pixel's color using some method and now I want to set the new color of that pixel.

How can I do ?

There is a setColor function. But I got the pixel from the Imagick class. But the setColor function is in the ImagickPixel class. So how can I do it ?


回答1:


->getImagePixelColor() returns an ImagickPixel object anyways, so $pixel->setColor(...); is all you need:

Ref: http://php.net/manual/en/imagick.getimagepixelcolor.php




回答2:


ImagickPixel::setColor() is the correct function but it is also necessary to sync the pixel Iterator so your manipulations are written back to the image.

Here is a short yet (almost) complete example that reads an image file, manipulates each pixel, and dumps it to a browser:

$img = new Imagick('your_image.png');

$iterator = $img->getPixelIterator();
foreach ($iterator as $row=>$pixels) {
  foreach ( $pixels as $col=>$pixel ){
    $color = $pixel->getColor();      // values are 0-255
    $alpha = $pixel->getColor(true);  // values are 0.0-1.0

    $r = $color['r'];
    $g = $color['g'];
    $b = $color['b'];
    $a = $alpha['a'];

    // manipulate r, g, b and a as necessary
    //
    // you could also read arbitrary pixels from 
    // another image with similar dimensions like so:
    // $otherimg_pixel = $other_img->getImagePixelColor($col,$row);
    // $other_color = $otherimg_pixel->getColor();
    //
    // then write them back into the iterator
    // and sync it

    $pixel->setColor("rgba($r,$g,$b,$a)");
  }
  $iterator->syncIterator();
}

header('Content-type: '.$img->getFormat());
echo $img->getimageblob();


来源:https://stackoverflow.com/questions/17367141/how-to-set-color-of-a-pixel-using-imagick-for-php-imagemagick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!