I`m working on a script that posts tweets to twitter with a random generated image with a random background color. Thats working perfectly but I want to show the rgb colors in the center of the image but its not working right. This is my code:
$rgbColor = array(rand(0,255),rand(0,255),rand(0,255));
$image = imagecreatetruecolor(600, 200);
$color = imagecolorallocate($image, $rgbColor[0], $rgbColor[1], $rgbColor[2]);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $color);
imagettftext($image, 20, 0,(300-(strlen('rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')')*20)/2), 75, (brghtdiff($rgbColor[0], $rgbColor[1], $rgbColor[2]) > 125 ? $black : $white), './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
imagejpeg($image, './image.jpg');
imagedestroy($image);
Creates:
Well, it displays the rgb(int, int, int) not in the center, does anyone know how the text can be in the center?
You are trying to determine the width of your text basing on its length multiplied by 20. This approach isn't correct because not all characters in your string have width of 20 pixels.
You should use imagettfbbox() function which will return array containing coordinates of corners of bounding box of your text. Basing on its result you can count real width of your text and position it correctly.
$bbox = imagettfbbox(20, 0, './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
$x = 300 - ($bbox[4] / 2);
imagettftext($image, 20, 0, $x, 75, (brghtdiff($rgbColor[0], $rgbColor[1], $rgbColor[2]) > 125 ? $black : $white), './Station.ttf', 'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
You need to know the size that the text will have with array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )
in your case:
$imBBox = imagettfbbox(20, 0, './Station.ttf',$text,'rgb('.$rgbColor[0].', '.$rgbColor[1].', '.$rgbColor[2].')');
Once you have the bounding box of your text, you can calculate the correct position of in the image so its centered.