tags:

views:

87

answers:

2

I am working on a captcha image type script and I am wanting to alternate each letters color on my image, so far I have it working pretty much except the color values are not what I expected

The colors in this $multi_text_color variable should be the colors that it randomly picks and shows, it does work in randomly picking the color array value however the colors it is putting on the image are 3 colors no where near to what I want, so am I doing something wrong here?

<?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});
}
?>
+1  A: 

imagecolorallocate() takes integers as parameters, not stings. Convert $r, $g and $b to integer first using hexdec().

Zed
A: 

If you are using hex numbers you need to convert them to decimals first.

$font_color = imagecolorallocate($image, hexdec($r), hexdec($g), hexdec($b));
RaYell
I actually originally had it as $font_color = imagecolorallocate($image, "0x$r", "0x$g", "0x$b"); but it displayed black text, I just tried again to make sure but it still shows black text this way, ill try the other way and see what happens, dont think any of this is gonna work it's weird
jasondavis
Ok the second one $font_color = imagecolorallocate($image, hexdec($r), hexdec($g), hexdec($b)); does work thank you so much! Any idea why the first method wouldn't work, I tried the first method earliar because I saw it working in another script but wouldn't in mine, thats whats weird
jasondavis
"0x$r" is still a string. You probably mean that one can enter the integer in hex form, e.g. 0xF6, but that doesn't help much in this case.
Zed
@Zed you are right, just checked that. I though that PHP weak typing can actualy convert `0xff` to valid hex but I was wrong. I have removed the incorrect part of my answer.
RaYell