Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将不透明像素转换为黑色_Php_Image Processing_Imagemagick - Fatal编程技术网

Php 将不透明像素转换为黑色

Php 将不透明像素转换为黑色,php,image-processing,imagemagick,Php,Image Processing,Imagemagick,我正在寻找一种转换图像的方法,使所有的非透明像素(那些alpha!=1)变成黑色和透明像素,而不被触摸(或转换成白色)。我最接近的方法是使用下面的imagemagick命令: convert <img> -colorspace Gray <out> 转换-颜色空间灰色 然而,这仍然给我一些灰色,而不是一个完整的黑色。我已经尝试了所有的色彩空间选项,但没有一个能做到这一点 你知道我如何使用imagemagick或类似工具(或PHP库,如果有的话)实现这一点吗?我不确定它

我正在寻找一种转换图像的方法,使所有的非透明像素(那些alpha!=1)变成黑色和透明像素,而不被触摸(或转换成白色)。我最接近的方法是使用下面的imagemagick命令:

convert <img> -colorspace Gray <out>
转换-颜色空间灰色
然而,这仍然给我一些灰色,而不是一个完整的黑色。我已经尝试了所有的色彩空间选项,但没有一个能做到这一点


你知道我如何使用imagemagick或类似工具(或PHP库,如果有的话)实现这一点吗?

我不确定它是否会帮助你(即,所提供的方法是否会忽略透明像素),但请查看这个问题的答案:

好吧,你可以使用GD和一对循环来实现这一点:

$img = imagecreatefromstring(file_get_contents($imgFile));
$width = imagesx($img);
$hieght = imagesy($img);

$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);

for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $width; $y++) {
        $color = imagecolorat($img, $x, $y);
        $color = imagecolorforindex($color);
        if ($color['alpha'] == 1) {
            imagesetpixel($img, $x, $y, $black);
        } else {
            imagesetpixel($img, $x, $y, $white);
        }
    }
}
$img=imagecreatefromstring(文件获取内容($imgFile));
$width=imagesx($img);
$hiight=imagesy($img);
$black=imagecolorallocate($img,0,0,0);
$white=imagecolorallocate($img,255,255,255);
对于($x=0;$x<$width;$x++){
对于($y=0;$y<$width;$y++){
$color=imagecolorat($img,$x,$y);
$color=imagecolorforindex($color);
如果($color['alpha']==1){
imagesetpixel($img,$x,$y,$black);
}否则{
imagesetpixel($img,$x,$y,$white);
}
}
}
或者,您可以替换颜色(这可能有效,也可能无效):

$img=imagecreatefromstring(文件获取内容($imgFile));
$maxcolors=imagecolorstotal($img);

因为($i=1;$i我知道这个问题很老了,但现在我无意中发现了,我还是回答它为好

所需的ImageMagick命令是:

convert <img> -alpha extract -threshold 0 -negate -transparent white <out>
转换

之后

convert <img> -alpha extract -threshold 0 -negate -transparent white <out>