使用PHP向图像添加文本 [英] Adding text to images with PHP
问题描述
我在向图像添加自定义文本时遇到了一些问题,我试图做的是将3行文本居中.但是,居中的文本在图像的右侧,而不是在图像的中心.到目前为止,这是我添加的文本,但是我需要使文本与图像上显示的行居中对齐.
I'm running into some issues with adding custom text to an image, what I am try to do is have 3 lines of text that is centered. However the centered text is on the right side of the image, not in the center of the image. This is what I have so far with text added, but I need to have the text aligned center with the line shown on the image.
// 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);
我也想从url中设置width变量,但是可以,但是我不确定如何调整文本大小以匹配调整后的图像.任何帮助将不胜感激.
I'm also wanting to make the width variable from the url, I can do but I'm not sure how to resize the text to match the resized image. Any assistance would be greatly appreciated.
推荐答案
您要为此使用imagettfbbox()来计算水平偏移量:
You want to use imagettfbbox() for this to calculate the horizontal offset:
$bbox = imagettfbbox(13, 0, $font_path, $text_line_1);
$xOffset = ($bbox[2] - $bbox[0]) / 2;
现在只需从所需位置减去偏移量即可.
Now just subtract the offset from your desired position and you are good to go.
这篇关于使用PHP向图像添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!