簡體   English   中英

動態GD圖像寬度文本

[英]Dynamic GD image width text

我試圖通過使用標題的自定義字體為我的網站增添趣味。 對我來說,最合適的方法是使用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 ?>

謝謝!

好的,我明白了! 對於可能遇到此問題的其他人,您需要添加:

// 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()之前

函數imagettfbbox將根據您選擇的字體計算文本的大小。 在調用imagecreatetruecolor時使用結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM