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
https://forums.phpfreaks.com/topic/96519-using-gd-to-create-a-text-image/
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

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);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.