如何在PHP中设置GD图像的正确颜色?

问题描述:

我正在处理一个验证码图像类型的脚本,我希望在我的图像上交替每个字母的颜色,到目前为止我的工作非常多,除了颜色值不是我期望的颜色值如何在PHP中设置GD图像的正确颜色?

此$ multi_text_color变量应该是它随机选取和显示的颜色,它可以随机选取颜色数组值 但是它在图像上的颜色是3种颜色,没有接近我想要的位置,所以我做错了什么这里?

<?PHP 
// note this is just the part I am having trouble with, I have taken everything else out that adds line and tilts the letters and stuff so just the color settings are in this bit 

// My this part of my script takes each number/letter in a string and makes it a random color to put on the image 

// set color values 
$multi_text_color = "#FF3E96,#6A5ACD,#90EE90"; 
// put colors above into an array 
$colors = explode(',', $multi_text_color); 
// cycle through everything to add the letters/numbers to image 
for($i = 0; $i < $characters; ++$i) { 
    $idx = rand(0, 2); 
    // notice my $colors variable has random number for the color array 
    $r = substr($colors[$idx], 1, 2); // shows: f6 or 8d or FF 
    $g = substr($colors[$idx], 3, 2); // shows: 3E or 32 or 5c 
    $b = substr($colors[$idx], 5, 2); // shows: 96 or 47 or fd 
    $font_color = imagecolorallocate($image, "$r", "$g", "$b"); 
    // finish it up 
    imagettftext($image, $font_size, $angle, $x, $y, $font_color, $this->font, $code{$i}); 
} 
?> 
+0

出于好奇,是否有一个原因,你没有使用预先构建的解决方案?除非你正在做一些完全创新的事情,否则很可能你的验证码很容易被破坏。 ReCaptcha使用来自书籍的扫描单词,一个尚未破解的系统,对残障用户提供了非常好的支持,并且设计精良以便于使用。 – Imagist 2009-08-01 06:45:00

如果您使用十六进制数字,您需要先将它们转换为小数点。

$font_color = imagecolorallocate($image, hexdec($r), hexdec($g), hexdec($b)); 
+0

我实际上最初的版本是$ font_color = imagecolorallocate($ image,“0x $ r”,“0x $ g”,“0x $ b”);但它显示黑色文本,我只是再次尝试确认,但它仍然显示这种方式的黑色文字,生病尝试另一种方式,看看会发生什么,不认为任何这是会工作这很奇怪 – JasonDavis 2009-08-01 05:44:10

imagecolorallocate()以整数作为参数,而不是刺激。使用hexdec()将$ r,$ g和$ b转换为整数。