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?