用GD改变图像颜色


Change image colors with GD

我想学习PHP中的图像处理,并编写一些代码来编辑照片。

所以,我正在阅读imagefilter()函数,但我想手动编辑颜色。

我有一小段代码使用imagefilter进行图像筛选

imagefilter($image, IMG_FILTER_GRAYSCALE); 
imagefilter($image, IMG_FILTER_COLORIZE, 55, 25, -10);
imagefilter($image, IMG_FILTER_CONTRAST, -10); 

我想做同样的事情,但没有imageffilter ();有可能吗?

我明白了,它可能在图像中获得颜色,然后改变它们并重新绘制它;

要获取图像颜色,我输入:

$rgb = imagecolorat($out, 10, 15);
$colors = imagecolorsforindex($out, $rgb);

打印:

array(4) { 
  ["red"]=> int(150) 
  ["green"]=> int(100) 
  ["blue"]=> int(15) 
  ["alpha"]=> int(0) 

}

我可以编辑这些值并将它们整合到图片中吗?

我将感谢任何形式的帮助:书籍,教程,代码块。

使用imagesetpixel()函数。因为这个函数需要一个颜色标识符作为第三个参数,所以你需要使用imagecolorallocate()来创建一个。

下面的示例代码将每种颜色的颜色值减半:

$rgb = imagecolorat($out, 10, 15);
$colors = imagecolorsforindex($out, $rgb);
$new_color = imagecolorallocate($out, $colors['red'] / 2, $colors['green'] / 2, $colors['blue'] / 2);
imagesetpixel($out, 10, 15, $new_color);

现在这里有一个简单的灰度过滤器:

list($width, $height) = getimagesize($filename);
$image = imagecreatefrompng($filename);
$out = imagecreatetruecolor($width, $height);
for($y = 0; $y < $height; $y++) {
    for($x = 0; $x < $width; $x++) {
        list($red, $green, $blue) = array_values(imagecolorsforindex($image, imagecolorat($image, $x, $y)));
        $greyscale = $red + $green + $blue;
        $greyscale /= 3;
        $new_color = imagecolorallocate($out, $greyscale, $greyscale, $greyscale);
        imagesetpixel($out, $x, $y, $new_color);
    }
}
imagedestroy($image); 
header('Content-Type: image/png');
imagepng($out);
imagedestroy($out);

在循环中使用imagecolorallocate时要小心,您不能在单个图像中分配比imagecolorstotal返回更多的颜色。如果您达到了限制imagecolorallocate将返回false,您可以使用imagecolorclosest来获得已经分配的壁橱颜色。