tags:

views:

319

answers:

3

Basically I am looking for a way to write dynamic text on top of a GIF [preferably via PHP GD.] But I can't seem to get these two functions to play nice.

For reference: imagecreatefromgif & imagettftext

function load_gif($imgname)
{
    $im = @imagecreatefromgif($imgname);

    if(!$im)
    {
        $im = imagecreatetruecolor(150,30);
        $bgc = imagecolorallocate($im,255,255,255);
        $tc = imagecolorallocate($im,0,0,0);

        imagefilledrectangle($im,0,0,150,30,$bgc);

        imagestring($im,1,5,5,'Error loading ' . $imgname,$tc);
    }

    return $im;
}

if ($_GET['color'] == 'red')
{
    header('Content-Type:image/gif');

    //$img = imagecreatetruecolor(51,32); // THIS IS NEEDED FOR TEXT TO SHOW
    $img = load_gif('map-bubble-' . $_GET['color'] . '.gif');

    $black = imagecolorallocate($img,0,0,0);
    $white = imagecolorallocate($img,255,255,255);

    imagefilledrectangle($img,0,0,51,32,$black);
    imagettftext($img,14,0,0,0,$white,'../arial.ttf','test');

    imagegif($img);

    imagedestroy($img);
}
+2  A: 

What if you create a new truecolour image, import the gif into that, add the text, then output the result again as a gif - you may have more luck that way.

Meep3D
Andrew G. Johnson
I guess I should specify: I think this is WHAT I need to do, the question is HOW
Andrew G. Johnson
A: 

Simply store the imagecreatefromgif into a variable, run imagettftext, then output the image using an content-type header. Take a look at the arguments, and fill in the $image argument with the outptu from imagecreatefromgif.

CodeJoust
Isn't that what I'm doing in my code sample?
Andrew G. Johnson
I wrote the answer before you posted the code. Sorry.
CodeJoust
A: 

Here's what I ended up doing:

if ($_GET['color'] == 'red' && strlen($_GET['number']) > 0 && is_numeric($_GET['number']))
{
    $image = imagecreatefromgif('map-bubble-' . $_GET['color'] . '.gif');

    $image_width = imagesx($image);

    $text_size = @imagettfbbox(10,0,'../arial.ttf','$' . $_GET['number']);
    $text_width = abs($text_size[2]-$text_size[0]);

    imagettftext($image,10,0,($image_width / 2) - ($text_width / 2),17,imagecolorallocate($image,255,255,255),'../arial.ttf','$' . $_GET['number']);

    header('Content-type:image/gif');
    imagegif($image);

    imagedestroy($image);
}
Andrew G. Johnson