如何使用php更改png图像像素值

如何使用php更改png图像像素值,php,Php,我正在尝试将图像中的白色像素更改为黑色,但在设置imagesetpixel 我在干什么 // get image data $image_data = imagecreatefrompng($image); // Turn off alpha blending imagealphablending($image_data, false); $width = imagesx($image_data); $height = imagesy($image_data); for($x = 0; $

我正在尝试将图像中的白色像素更改为黑色,但在设置
imagesetpixel

我在干什么

// get image data
$image_data = imagecreatefrompng($image);

// Turn off alpha blending
imagealphablending($image_data, false);

$width = imagesx($image_data);
$height = imagesy($image_data);

for($x = 0; $x < $width; $x++) {
    for($y = 0; $y < $height; $y++) {
        // pixel color at (x, y)
       $color = imagecolorsforindex($image_data, imagecolorat($image_data, $x, $y)); // human readable
        // check if we have white
        if(
            $color['red'] == 255 &&
            $color['green'] == 255 &&
            $color['blue'] == 255 &&
            $color['alpha'] == 127
        ){    
            //  make it black
            $color['red'] == 0
            $color['green'] == 0
            $color['blue'] == 0 
            imagesetpixel($image_data, $x, $y, $color );  // $color format not OK.
        } 
    }
}

    // Set alpha flag
    imagesavealpha($image_data, true);  
    //  https://www.php.net/manual/en/function.imagepng.php
    imagepng($image_data , "path to save png");
    imagedestroy($image_data);
//获取图像数据
$image\u data=imagecreatefrompng($image);
//关闭alpha混合
imagealphablending($image_数据,false);
$width=imagesx($image\u数据);
$height=imagesy($image\u数据);
对于($x=0;$x<$width;$x++){
对于($y=0;$y<$height;$y++){
//(x,y)处的像素颜色
$color=imagecolorsforindex($image_数据,imagecolorat($image_数据,$x,$y));//人类可读
//看看有没有白色的
如果(
$color['red']==255&&
$color['green']==255&&
$color['blue']==255&&
$color['alpha']==127
){    
//把它弄黑
$color['red']==0
$color['green']==0
$color['blue']==0
imagesetpixel($image_data,$x,$y,$color);//$color格式不正常。
} 
}
}
//设置alpha标志
imagesavealpha($image_data,true);
//  https://www.php.net/manual/en/function.imagepng.php
imagepng($image_data,“保存png的路径”);
imagedestroy($image\u数据);
那么,您知道如何将
imagecolorsforindex
返回格式转换为与
imagesetpixel
兼容的格式吗 $color['red']==0 $color['green']==0 $color['blue']==0 imagesetpixel($image_data,$x,$y,$color);//$颜色格式不正常。 不遵循错误指示的样式:

未捕获的TypeError:imagesetpixel():参数#4($color)必须是int类型,数组给定


让我们解决这个问题,考虑下面的例子:

//创建黑色(rgb)
$black=imagecolorallocate($image_数据,0,0,0);
//把它弄黑
imagesetpixel($image\u data,$x,$y,$black);
在这里,我们使用创建“黑色”,它被
imagesetpixel
接受为一种颜色。
$image\u数据
x
y
都很好,我们会保持原样


另外,我创建了一个简单的测试图像来检查它是否工作,但是,您的检查没有触发MacOs preview创建的简单白色像素,
alpha
被设置为
0
,因此对于我的测试,我要做以下更改:

if(
$color['red']==255&&
$color['green']==255&&
$color['blue']==255//&&
//$color['alpha']==127
)