tags:

views:

507

answers:

2

Hi all,

I have a collection of black and white JPEG's stored on my server. These images are symbol based, where the symbol is a collection of black lines on a white background.

I am trying to use GD to replace the black colour with another colour on the fly based on a variable passed. Currently, I am:

Getting the JPEG as: $image = imagecreatefromjpeg($imgURL), Converting a HEX code (#FF0000, say) to RGB through PHP,

And then feeding these variables to:

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 a new colour).

Can anyone advise as to where I am going wrong?

Many thanks.

A: 

If the color is the only problem, then you could try this:

      <php>
      //SNIP
      $color = preg_replace('/^#/','',$color); //Get rid of "#" 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>

Eddy
A: 

You can use the imageistruecolor function to find out whether the JPEG you've just loaded is true colour or palette-based. If it's not true colour, you can create a new true color image of the same width and height, and copy the old image over:

$width = imagesx($jpeg);
$height = imagesy($jpeg);
$image = imagecreatetruecolor($width, $height);
imagecopy($jpeg, $image, 0, 0, 0, 0, $width, $height);

You should then be able to apply the new colours.

Samir Talwar