我的解决方案是建立在多个建议的基础上。我查看了StackOverflow有关分割赏金的政策,发现这是不可能的。赏金必须授予一个全面的答案。如果有其他方法可以将我的赏金分给所有在此回复/评论的人,请与我联系。
我没有太多运气找到好看的.gdf字体。它指引我使用imagestring
绘制文本而无需任何字体文件(gdf或ttf)-请参阅php文档。'默认'字体只是一些等宽字体,不太漂亮,但作为备选项很好用。
为避免.ttf锁定,我将尝试查找操作系统字体文件夹并从那里加载字体。这已在我的Windows开发机上进行了测试。如果找不到.ttf文件,则会使用imagestring
的本地字体备选项。
我选择了面向对象的方法来抽象化文本如何写入图像。
abstract class TextWriter {
public static function getInstance() {
$osName = php_uname( 's' );
if (strtoupper(substr($osName, 0, 3)) === 'WIN') {
$path = 'C:/Windows/Fonts/';
} else if (strtoupper(substr($osName, 0, 5)) === 'LINUX') {
$path = '/usr/share/fonts/truetype/';
} else if (strtoupper(substr($osName, 0, 7)) === 'FREEBSD') {
$path = '/usr/local/lib/X11/fonts/TrueType';
}
if (is_dir($path) && is_file($path . "/arial.ttf")) {
return new TTFTextWriter($path . "/arial.ttf");
}
return new NativeTextWriter();
}
abstract public function get_dimenions($string);
abstract public function write_text($img_resource, $x, $y, $text, $color);
}
class TTFTextWriter extends TextWriter {
private $ttf_file;
private $fontsize = 10;
public function __construct($ttf_file) {
$this->ttf_file = $ttf_file;
}
public function get_dimenions($text) {
$dimenions = imagettfbbox($this->fontsize, 0, $this->ttf_file, $text);
return array($dimenions[2], abs($dimenions[5] - $dimenions[3]));
}
public function write_text($img_resource, $x, $y, $text, $color) {
imagettftext($img_resource, $this->fontsize, 0, $x, $y, $color, $this->ttf_file, $text);
}
}
class NativeTextWriter extends TextWriter {
private $fontsize = 3;
private $text_width = 7;
private $text_height = 15;
public function get_dimenions($text) {
return array(strlen($text) * $this->text_width, $this->text_height);
}
public function write_text($img_resource, $x, $y, $text, $color) {
imagestring($img_resource, $this->fontsize, $x, $y - $this->text_height, $text, $color);
}
}
使用方法:
$writer = TextWriter::getInstance();
$dimenions = $writer->get_dimenions($text);
$width = $dimenions[0];
$height = $dimenions[1];
$im = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($im, 1, 1, 1);
$writer->write_text($im, 0, 0, $text, $black);
header('Content-Type: image/gif');
imagegif($im);
imagedestroy($im);