Issue
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.
First, I have an original image, which is a true-color image. It is saved in JPEG format:
This original picture has: 16 777 216 colors.
Then, I could convert it into a gray-scale image, after running this simple script:
<?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);
?>
And, below is result:
This gray-scale picture has: 256 colors.
Now, I want to convert it into a real one-color image:
This one-color picture has: 1 color.
In this case, $MyColor = #000000;
.
Can you show me: How to convert a true-color image to an one-color image, with PHP?
Solution
Just two lines of code will handle the grey scale conversion and reducing the image to only two colours (because a one-colour image is a blank canvas), with dithering:
$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);
Result:
Answered By - timclutton Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.