我一直在使用這個簡單的腳本來從文字圖像的圖像格式的文本:使用PHP GD創建具有不同的字體
<?php
header('Content-type: image/png');
$color = RgbfromHex($_GET['color']);
$text = urldecode($_GET['text']);
$font = 'arial.ttf';
$im = imagecreatetruecolor(400, 30);
$bg_color = imagecolorallocate($im, 255, 255, 255);
$font_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);
imagefilledrectangle($im, 0, 0, 399, 29, $bg_color);
imagettftext($im, 20, 0, 10, 20, $font_color, $font, $text);
imagepng($im);
imagedestroy($im);
function RgbfromHex($hexValue) {
if(strlen(trim($hexValue))==6) {
return array(
hexdec(substr($hexValue,0,2)), // R
hexdec(substr($hexValue,2,2)), // G
hexdec(substr($hexValue,4,2)) // B
);
}
else return array(0, 0, 0);
}
?>
我打電話與file.php文本=測試腳本&顏色腳本= 000000
現在我想知道我怎麼能生成相同的圖像在混合正常和加粗字體的文本,像file.php?text=testing <b>script</b>&color=000000
謝謝到dqhendricks幫我解決這個問題。
下面是一個簡單的腳本我寫的,還需要改進很多,但對於基本功能,這似乎是做工精細:
<?php
header('Content-type: image/png');
$color = RgbfromHex($_GET['color']);
$im = imagecreatetruecolor(400, 30);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
$tmp = $_GET['text'];
$words = explode(" ", $tmp);
$x = array(0,0,10); // DUMMY ARRAY WITH X POSITION FOR FIRST WORD
$addSpace = 0;
foreach($words as $word)
{
if($addSpace) $word = " ".$word; // IF WORD IS NOT THE FIRST ONE, THEN ADD SPACE
if(stristr($word, "<b>"))
{
$font = 'arialbd.ttf'; // BOLD FONT
$x = imagettftext($im, 20, 0, $x[2], 20, imagecolorallocate($im, $color[0], $color[1], $color[2]), $font, str_replace(array("<b>","</b>"), "", $word));
}
else
{
$font = 'arial.ttf'; // NORMAL FONT
$x = imagettftext($im, 20, 0, $x[2], 20, imagecolorallocate($im, $color[0], $color[1], $color[2]), $font, $word);
}
$addSpace = 1;
}
imagepng($im);
imagedestroy($im);
function RgbfromHex($hexValue) {
if(strlen(trim($hexValue))==6) {
return array(
hexdec(substr($hexValue,0,2)), // R
hexdec(substr($hexValue,2,2)), // G
hexdec(substr($hexValue,4,2)) // B
);
}
else return array(0, 0, 0);
}
?>
注:這隻會爲「加粗」用空格分隔單個單詞工作而不是拼寫單詞的一部分。
呼叫與file.php?text=testing+<b>script</b>&color=000000
嘗試http://www.roseindia.net/tutorial/php/phpgd/About-boldtext.html它似乎你想要做什麼,它的黑色字體,是在灰色字體的頂部,你可以改變灰色的位置,讓它們被放置在你喜歡的位置。該URL將類似於`file.php?text = testing&bold = script&color = 000000`。 – Daniel 2011-01-09 01:09:01
這看起來不像大膽,但更像是一個影子,如果我把它放在彼此的前面,我不認爲它們會出現任何不同,因爲只有一個imagettftext()。 – Meredith 2011-01-09 02:45:21