Jump to content

Using GD to create a text image


c_shelswell

Recommended Posts

Hi,

 

I'm looking to make a selection of text headers for multiple sites using different fonts so I thought I'd try and use php to automate the process for me. Writing the text seems easy enough (imagettftext) but what i'm struggling with is how to set the size of the image to only be as big as is required by the length of the string i'm passing imagettftext.

 

Is there anyway to do this?

 

Cheers

Link to comment
Share on other sites

You could always just play around with certain sizes till you get a base. Lets say it take 15 pixels to create one letter with a space, you could get the length of the string and multiply it by the value.

 

$text = "menu Item";

$length = strlen($text);

$value = 15;

 

$width = $length * $value;

 

that way it will be dynamic.

 

Ray

Link to comment
Share on other sites

If you are using the gd monospaced fonts

<?php
$text = 'Hello World';
$w = imagefontwidth(5) * strlen($text);
$h = imagefontheight(5);

$im = imagecreate ($w + 10, $h+10);
$bg = imagecolorallocate($im, 200, 200, 200);
$tcol = imagecolorallocate($im, 255, 0, 0);

imagestring($im, 5, 5, 5, $text, $tcol);

header("content-type: image/png");
imagepng ($im);
imagedestroy($im);
?>

 

If you use truetype font

<?php
$text = 'Hello World';

$bb = imagettfbbox(20, 0, 'c:/windows/fonts/arial.ttf', $text);
$w = abs($bb[4] - $bb[0]);
$h = abs($bb[5] - $bb[1]);

$im = imagecreate ($w + 20, $h+20);
$bg = imagecolorallocate($im, 200, 200, 200);
$tcol = imagecolorallocate($im, 255, 0, 0);

imagettftext($im, 20, 0, 10, $h+10, $tcol, 'c:/windows/fonts/arial.ttf', $text);

header("content-type: image/png");
imagepng ($im);
imagedestroy($im);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.