动态GD图像宽度文本
我正在尝试通过使用自定义字体来为我的网站增添趣味。对我来说,最合适的方法是使用 PHP 和 GD。我编写了一个小脚本,它将根据 $_GET 值输出动态文本,但有时图像太宽,这会移动其他所有内容。
如何让图像根据文本的宽度调整其宽度?这是我到目前为止编写的代码:
<?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 ?>
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我明白了!对于可能遇到此问题的其他人,您需要添加:
在 imagecreatetruecolor() 之前
Ok, I figured it out! For anyone else who may have this problem, you need to add:
Before the imagecreatetruecolor()
函数 imagettfbbox 将根据您选择的字体计算文本的大小。在调用 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.