我想在jpg上写一些文字。我使用php函数"imagefttext“。问题是,我想指定文本框的宽度。
换句话说:如何在900px x 400px图像上的300px x 300px区域中写入文本。
我该怎么做呢?
发布于 2011-02-22 23:29:27
这篇文章应该会有所帮助:
//由于新的用户限制,必须删除
以及:http://uk.php.net/manual/en/ref.image.php
编辑,因为你似乎不想自己去找;)
http://php.net/manual/en/function.imagettfbbox.php
$box = @ImageTTFBBox($font_size,0,$font_file,$text) ;
$text_width = abs($box[2]-$box[0]);
$text_height = abs($box[5]-$box[3]);
$image_width = imagesx($image);
$text_x = $image_width - $text_width - ($image_width - $x_finalpos);
这至少应该能让你开始。在我链接的php手册页面上有更详细的示例:)
您需要编写一个函数来检查每一行的长度,并将其拆分,直到它适合您指定的边界框。我还注意到在php手册页面下面的注释中有一些函数可以换行文本,这也会给你一个很好的起点!:)
<?php
$mx = imagesx($main_img);
$my = imagesy($main_img);
//TEXT VARS/////////
$main_text = ;
$main_text_size = ;
$main_text_x = ($mx/2);
$main_text_color = imagecolorallocate($main_img, $main_text_red, $main_text_green, $main_text_blue);
$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;
for($i = 1; $i < count($words); $i++)
{
$lineSize = imagettfbbox($main_text_size, 0, $mt_f, $lines[$currentLine] . ' ' . $words[$i]);
if($lineSize[2] - $lineSize[0] < $mx)
{
$lines[$currentLine] .= ' ' . $words[$i];
}
else
{
$currentLine++;
$lines[$currentLine] = $words[$i];
}
}
$line_count = 1;
// Loop through the lines and place them on the image
foreach ($lines as $line)
{
$line_box = imagettfbbox($main_text_size, 0, $mt_f, "$line");
$line_width = $line_box[0]+$line_box[2];
$line_height = $line_box[1]-$line_box[7];
$line_margin = ($mx-$line_width)/2;
$line_y = (($line_height+12) * $line_count);
imagettftext($main_img, $main_t_s, 0, $line_margin, $line_y, $main_text_color, $mt_f, $line);
// Increment Y so the next line is below the previous line
$line_count ++;
}
?>
我还没有测试过这一点,而且很可能还有更好的例子。尝试在php手册中查找注释或在google上查找"PHP图片文本环绕“,您将找到一些内容:)
玩得开心!
https://stackoverflow.com/questions/5079976
复制相似问题