如何使用 PHP 将 "true-color" 图像转换为 "one-color" 图像?

How to convert a "true-color" image to an "one-color" image, with PHP?

I have read all related questions on Stack Overflow, which has a group-of-word: black-and-white or monochrome. These posts are discussed about one of two common problems: gray-scale or black-and-white.

I do not want my output image in black-color only; but, I want more. I want my output picture in one-color, which is given by a variable, for instance: $MyColor = #336699;, $MyColor = #3366CC; ...

So, my question is not duplicated with any existed question.


首先,我有一张原始图像,它是一张真彩色图像。它以JPEG格式保存:

这张原图有:16 777 216 种颜色。


然后,在 运行 这个简单的脚本之后,我可以将它转换成 灰度 图像:

<?php 

$source_file = "1.JPG";

$im = ImageCreateFromJpeg($source_file); 

$imgw = imagesx($im);
$imgh = imagesy($im);

for ($i=0; $i<$imgw; $i++)
{
        for ($j=0; $j<$imgh; $j++)
        {

                // Get the RGB value for current pixel

                $rgb = ImageColorAt($im, $i, $j); 

                // Extract each value for: R, G, B

                $rr = ($rgb >> 16) & 0xFF;
                $gg = ($rgb >> 8) & 0xFF;
                $bb = $rgb & 0xFF;

                // Get the value from the RGB value

                $g = round(($rr + $gg + $bb) / 3);

                // Gray-scale values have: R=G=B=G

                $val = imagecolorallocate($im, $g, $g, $g);

                // Set the gray value

                imagesetpixel ($im, $i, $j, $val);
        }
}

header('Content-type: image/jpeg');
imagejpeg($im);

?>

下面是结果:

这张灰度图片有:256 种颜色。


现在,我想将其转换成真实 单色图像:

这张单色图片有:1种颜色。

在这种情况下,$MyColor = #000000;


你能告诉我:如何使用 PHP 将真彩色图像转换为单色图像?

只需两行代码即可处理灰度转换并将图像缩小为只有两种颜色(因为单色图像是空白 canvas),抖动:

$img = imagecreatefromjpeg('./38519049.jpg');

imagefilter($img, IMG_FILTER_GRAYSCALE); // convert to grey scale.
imagetruecolortopalette($img, true, 2); // 'true' for dithering, '2' for number of colours.

header('Content-type: image/jpeg');
imagejpeg($img);

结果: