有一个excellent answer关于如何使用 PHP-GD 库更改图像的色调。但我需要知道如何使用 PHP-GD 更改图像的饱和度。这是答案中的代码副本,它成功更改了图像的色调。
function imagehue(&$image, $angle) {
if($angle % 360 == 0) return;
$width = imagesx($image);
$height = imagesy($image);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
list($h, $s, $l) = rgb2hsl($r, $g, $b);
$h += $angle / 360;
if($h > 1) $h--;
list($r, $g, $b) = hsl2rgb($h, $s, $l);
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
}
}
}
如果您需要查看辅助函数的代码rgb2hsl
和hsl2rgb
请查看original answer 。自 Hue
是 HSL 的参数之一,我想我可以以某种方式修改该函数以获得饱和度的有效解决方案。尽管我的 PHP 技能有限,但我不得不尝试,但它不起作用并产生了奇怪的结果。这是我正在尝试的修改。
修改代码:按照@mark的建议更新
function imageSaturation(&$image, $saturationPercentage) {
$width = imagesx($image);
$height = imagesy($image);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
list($h, $s, $l) = rgb2hsl($r, $g, $b);
$s = $s * (100 + $saturationPercentage ) /100;
if($s > 1) $s = 1;
list($r, $g, $b) = hsl2rgb($h, $s, $l);
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
}
}
}
header('Content-type: image/png');
$image = imagecreatefrompng('rgb.png');
imageSaturation($image, -80);//bring down current image saturation to 80%
imagepng($image);
努力更新: @Dai 向我指出,这些线有助于构建单个 RGB 像素的颜色代码。所以我想这部分可以保持不变吗?
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
在下一行中,我们只是使用 rgb2hsl($r, $g, $b);
将 RGB 值转换为 HSL。并将其分配给 list($h, $s, $l)
。我现在遇到的问题是这些行。
$s += $saturationPercentage / 100;
if($s > 1) $s--;
我理解语法,但不确定如何处理这些或者是否需要它们。如果没有答案,有帮助的提示/建议会很棒。我正在尝试 this image 上的代码将饱和度从 100% 降低到 80%,但我得到 this image结果。
最佳答案
有一个更简单、更快捷的解决方案来降低颜色饱和度:
- 创建图像的黑白克隆
- 将黑白克隆与原始图像混合
代码是这样的:
function imageSaturation($im, $percentage) /* $percentage to be between 0 and 100 */
{
$width = imagesx($im);
$height = imagesy($im);
$im2 = imagecreatetruecolor($width, $height);
imagecopy($im2, $im, 0, 0, 0, 0, $width, $height);
imagefilter($im2, IMG_FILTER_GRAYSCALE);
imagecopymerge($im, $im2, 0, 0, 0, 0, $width, $height, 100-$percentage);
imagedestroy($im2);
}
关于php - 使用PHP GD库更改图像的 “Saturation”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001508/