【问题标题】:Dynamic GD image width text动态GD图像宽度文字
【发布时间】:2010-12-16 19:43:15
【问题描述】:

我正在尝试通过为标题使用自定义字体来为我的网站增添趣味。对我来说,最合适的方法是使用 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 ?>

谢谢!

【问题讨论】:

    标签: php fonts gd width


    【解决方案1】:

    函数imagettfbbox 将根据您选择的字体计算文本的大小。在调用 imagecreatetruecolor 时使用结果。

    【讨论】:

    • 我似乎无法让它工作,它会破坏图像或导致错误?
    【解决方案2】:

    好的,我想通了!对于其他可能遇到此问题的人,您需要添加:

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

    在 imagecreatetruecolor() 之前

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2010-12-17
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多