Adding text to images with PHP

2019-08-20 05:53发布

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);

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.

Current Placement of Text

What I am wanting

1条回答
该账号已被封号
2楼-- · 2019-08-20 06:40

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.

查看更多
登录 后发表回答