问题
There are images I want to remove the background of (or set it to transparent rather). For that reason, I have tested a bash imagick command that looks like this:
convert test.jpg -alpha set -channel RGBA -bordercolor white -border 1x1 -fuzz 2% -fill none -floodfill +0+0 white -shave 1x1 test.png
Because I need to use this in my php
script, I need to translate this over now. What I've come up with is this:
$imagick->readImage($path);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
$imagick->borderImage('white', 1, 1);
$imagick->floodFillPaintImage('transparent', 20, 'white', 0, 0, false);
$imagick->shaveImage(1, 1);
$imagick->writeImage(str_replace('.jpg', '.png', $path));
From what I can tell, it generates the image and it removes big parts of the background. But the fuzziness setting seems to be ignored.
The results of this script are always the same as when I use -fuzz 0%
in the command prompt, no matter what fuzziness value I pass. Am I doing something wrong or is there a bug (which would leave me searching for another script capable of doing this)?
回答1:
Am I doing something wrong or is there a bug
Let's call it a documentation error.
Imagick::floodFillPaintImage (and most of the other functions that take a fuzz parameter) need to have the fuzz scaled to the quantum range that ImageMagick was compiled with. e.g. for ImageMagick compiled with 16 bits of depth, the quantum range would be (2^16 - 1) = 65535
There is an example at http://phpimagick.com/Imagick/floodFillPaintImage
$imagick->floodFillPaintImage(
$fillColor,
$fuzz * \Imagick::getQuantum(),
$targetColor,
$x, $y,
$inverse,
$channel
);
So the reason that you're seeing the output image be the same as if you had passed in 0 fuzz, is that ImageMagick is interpreting the value of 2 that you are passing in as 2 / 65535 .... which is approximately zero.
来源:https://stackoverflow.com/questions/32155285/imagick-convert-bash-command-into-php-script