使用PHP

时间:2018-01-08 18:28:01

标签: php image text imagettftext

我在向图像添加自定义文本时遇到了一些问题,我尝试做的是有3行文本居中。但是,居中文本位于图像的右侧,而不是图像的中心。这是我到目前为止添加了文本的内容,但我需要将文本与图像上显示的行对齐。

// Variables
$img = LoadJpeg('img/custom-image.jpg');
$orig_width = imagesx($img);
$orig_height = imagesy($img);
$width = 2500;
$font_path = 'font/ArialBlack.ttf';
$text_line_1 = $_GET['series'];
$text_line_2 = $_GET['custom'];
$text_line_3 = $_GET['model'];


// Calc the new height
$height = (($orig_height * $width) / $orig_width);

// Create new image to display
$new_image = imagecreatetruecolor($width, $height);

// Create some colors
$white = imagecolorallocate($new_image, 255, 255, 255);

// Create new blank image with changed dimensions
imagecopyresized($new_image, $img,0, 0, 0, 0, $width, $height, $orig_width, $orig_height);

// Add text to image
imagettftext($new_image, 13,0, 2150,72, $white, $font_path, $text_line_1);
imagettftext($new_image, 13,0, 2150,92, $white, $font_path, $text_line_2);
imagettftext($new_image, 13,0, 2150,112, $white, $font_path, $text_line_3);

// Print image
imagejpeg($new_image);

imagejpeg($img);
imagedestroy($img);

我也想从网址创建宽度变量,我可以做,但我不知道如何调整文本大小以匹配调整大小的图像。非常感谢任何帮助。

Current Placement of Text

What I am wanting

1 个答案:

答案 0 :(得分:0)

您希望使用imagettfbbox()来计算水平偏移:

$bbox = imagettfbbox(13, 0, $font_path, $text_line_1);
$xOffset = ($bbox[2] - $bbox[0]) / 2;

现在只需从您想要的位置减去偏移量,就可以了。