Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic GD image width text

Tags:

php

width

fonts

gd

I'm trying to spice up my website by using custom fonts for headings. For me, the most appropriate way to do this is using PHP and GD. I have written a little script which will output the dynamic text based on the $_GET value, however sometimes the image is too wide, which moves everything else about.

How can I get the image to adjust the width of it, based on the width of the text? Here is the code I've written so far:

<?php
// Settings
$sText = $_GET['t']; // Text of heading
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it

// Create the image
header("content-type: image/png"); // Set the content-type
$hImage = imagecreatetruecolor(200, 24);
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT);
imagesavealpha($hImage, true);
imagealphablending($hImage, false);
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text
imagepng($hImage); // Generate the image
imagedestroy($hImage); // Destroy it from the cache ?>

Thanks!

like image 338
James Brooks Avatar asked Dec 29 '22 11:12

James Brooks


1 Answers

Ok, I figured it out! For anyone else who may have this problem, you need to add:

// Calcuate the width of the image
$arSize = imagettfbbox(24, 0, $sFont, $sText);
$iWidth = abs($arSize[2] - $arSize[0]);
$iHeight = abs($arSize[7] - $arSize[1]);

Before the imagecreatetruecolor()

like image 137
James Brooks Avatar answered Jan 12 '23 00:01

James Brooks