Color overlay on JPEG using PHP / GD?
I have a collection of black and white JPEGs stored on my server. These images are symbol based, where the symbol is a set of black lines on a white background.
I am trying to use GD to replace black with a different color on the fly based on a passed variable. I am currently:
Getting JPEG as: $ image = imagecreatefromjpeg ($ imgURL), Convert HEX code (# FF0000, say) to RGB via PHP,
And then loading these variables into:
private function colourize_image($image, $colour, $contrast = 0) {
if (!$image) { return false; }
imagealphablending($image, true);
imagesavealpha($image, true);
# Convert hex colour into RGB values
$r = hexdec('0x' . $colour{0} . $colour{1});
$g = hexdec('0x' . $colour{2} . $colour{3});
$b = hexdec('0x' . $colour{4} . $colour{5});
imagefilter($image, IMG_FILTER_COLORIZE, $r, $g, $b);
imagefilter($image, IMG_FILTER_CONTRAST, $contrast);
# Return the GD image object
return $image;
}
For some reason, the function doesn't work at all (it won't overlay the new color).
Can anyone advise on where I am going wrong?
Many thanks.
source to share
If color is the only problem, you can try this:
<php>
// SNIP $ color = preg_replace ('/ ^ # /', '', $ color); // Get rid of the "#" if it's there $ r = hexdec ("0x {$ color [0]} {$ color [1]}" ); $ g = hexdec ("0x {$ color [2]} {$ color [3]}");
$ b = hexdec ("0x {$ color [4]} {$ color [5]}"); // SNIP </php>
source to share
You can use the function imageistruecolor
to find out if the JPEG you just loaded is a true color or palette. If it is not a true color, you can create a new true color image of the same width and height and copy the old image:
$width = imagesx($jpeg);
$height = imagesy($jpeg);
$image = imagecreatetruecolor($width, $height);
imagecopy($jpeg, $image, 0, 0, 0, 0, $width, $height);
Then you can apply new colors.
source to share