我正在使用PHP GD库将一串文本添加到图像上。
字符串可以是2行,或3。
问题在于它正在使用带有\ n换行符的字符串,然后将其居中,但它不是居中的第二行。
它会创建如下图像:
当我希望它以两条线为中心时。
这是我的代码:
header('Content-type: image/jpeg');
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$black = imagecolorallocatealpha($image, 0, 0, 0, 40);
imagefilledrectangle($image, 0, 0, $imagewidth, 207, $black);
$white = imagecolorallocate($image, 255, 255, 255);
$text = wordwrap($_POST['headline'], 33, "\n" );
$font = 'HelveticaWorld-Bold.ttf';
$fontsize = 45;
$fontangle = 0;
### Get exact dimensions of text string
$box = @imageTTFBbox($fontsize, $fontangle, $font, $text);
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth / 2) - ($textwidth / 2) - 2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2);
$ycord = 80;
function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
$bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}
### imagettftext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $font, $text);
$stroke_color = imagecolorallocate($image, 0, 0, 0);
imagettfstroketext($image, $fontsize, $fontangle, $xcord, $ycord, $white, $stroke_color, $font, $text, 7);
imagejpeg($image, NULL, 100);
imagedestroy($image);