PHP imagecolorallocate() & imagettftext() always generating black text

Indunil Ramadasa
1 min readDec 21, 2020

--

Today I encountered an issue with using PHP function imagettftext() for generating an image with some text. I was using the usual imagecolorallocate() function for generating color identifier.

$txt_font_color = imagecolorallocate($image3, $component_config['font_color']['r'], $component_config['font_color']['g'], $component_config['font_color']['b']);

imagettftext( $image3, $txt_font_size, $angel, $x, $y, $txt_font_color, $txt_font, $line );

Surprisingly it was generating black-colored text despite the set pure white color. Then I tried with giving different color codes and always it was generating black.

Later after googling on the issue, I found out that it is somewhat common. I was using a PNG with 8-bit palette. Apparently it given text color rgb(255,255,255) had been not in the palette of source image. In such cases function imagecolorallocate() returns false as it fails to process it.

The solution :

I used imagecolorclosest() function instead imagecolorallocate(). It solved the problem.

$txt_font_color = imagecolorclosest($image3, $component_config['font_color']['r'], $component_config['font_color']['g'], $component_config['font_color']['b']);

I also read that imagecreatetruecolor() along with imagecolorallocate() is also a solution.

Obviously there would be other solutions for this issue including changing the source image :) .

--

--