创建了一张800x600像素的纯白海报图,
并在中央添加了一个黑色“你好”的文本,字体为微软雅黑,字体大小为40。
你可以根据自己的需求修改代码。
注意,在使用GD库渲染中文字符时,不仅要指定字体文件路径和字体大小,
还需要通过imagettfbbox()
函数获得文字宽高,以便于在图像中居中绘制。
<?php
// 创建画布
$width = 800;
$height = 600;
$im = imagecreatetruecolor($width, $height);
// 设置背景色
$bgColor = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bgColor);
// 设置字体路径和字体大小
$fontFile = 'msyh.ttf';
$fontSize = 40;
// 添加文本
$textColor = imagecolorallocate($im, 0, 0, 0);
$text = '你好';
$textWidth = imagettfbbox($fontSize, 0, $fontFile, $text)[2] - imagettfbbox($fontSize, 0, $fontFile, $text)[0];
$textHeight = imagettfbbox($fontSize, 0, $fontFile, $text)[3] - imagettfbbox($fontSize, 0, $fontFile, $text)[5];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 - 30; // 为了让字体居中,往上偏移一点
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $fontFile, $text);
// 保存图像
$imageFile = 'poster.png';
imagepng($im, $imageFile);
// 销毁图像
imagedestroy($im);