John Davidson

Center multi line text over image with PHP

0 comments
Message:


I want to make a generator for text over a specific image (what I kind of exactly want is: https://www.wijsheidspreuk.nl/tegeltjesmaker, only I want to make an API for Discord of it).


I've tried some things, but can't get the text centered on the image. Especially when I have multiple lines of text. The code I have now is this:


<?php
header("content-type: image/png");
imagepng(errorimage("Multiple lines of text \n more multiple lines of text \n another line of lines bla bla text text"));

function errorimage($text, $target_size = null)
{
$width = 0;
$height = 0;
$border_size = 150; // in px, if $target_size isn't null has no effect
$line_spacing = 2; // in px
$font_size = 10; // 1 - 5

$font_width = imagefontwidth($font_size); // in px
$font_height = imagefontheight($font_size); // in px
$text_lines = array_map("trim", explode("\n", $text));

if(!empty($target_size)) {
$width = $target_size;
$height = $target_size * (2 / 3);
}
else {
$height = count($text_lines) * $font_height +
(count($text_lines) - 1) * $line_spacing +
$border_size * 2;
foreach($text_lines as $line)
$width = max($width, $font_width * mb_strlen($line));
$width += $border_size * 2;
}

$image = imagecreatefromjpeg("images/base.jpg");

$i = 0;
foreach($text_lines as $line) {
imagestring($image, $font_size,
($width / 2) - (($font_width * mb_strlen($line)) / 2),
$border_size + $i * ($font_height + $line_spacing),
$line,
imagecolorallocate($image, 68, 39, 113) // #442772
);
$i++;
}

return $image;
}
?>

The result that comes out of it:



Any ideas / libraries which would fix this?



My Answer:
php

// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Set the font size and color
$font_size = 20;
$font_color = imagecolorallocate($image, 255, 255, 255);

// Set the text to be displayed
$text = "This is a multi line text example";

// Calculate the position to center the text
$text_box = imagettfbbox($font_size, 0, 'arial.ttf', $text);
$text_width = $text_box[2] - $text_box[0];
$text_height = $text_box[1] - $text_box[7];
$image_width = imagesx($image);
$image_height = imagesy($image);
$x = ($image_width - $text_width) / 2;
$y = ($image_height - $text_height) / 2 + $font_size;

// Write the text on the image
imagettftext($image, $font_size, 0, $x, $y, $font_color, 'arial.ttf', $text);

// Output the image
header('Content-Type: image/jpeg');
imagejpeg($image);

// Free up memory
imagedestroy($image);

?>


This code should center the multi line text over the image. Make sure to replace 'image.jpg' with the path to your image file and 'arial.ttf' with the path to your font file. You can adjust the font size and color to fit your needs.

Rate this post

5 of 5 based on 4952 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us