English 中文(简体)
Dynamic GD image width text
原标题:

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!

最佳回答

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()

问题回答

The function imagettfbbox will calculate the size of what the text will be based on the font you picked. Use the results in your call to imagecreatetruecolor.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签