0

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:

Result of script

Any ideas / libraries which would fix this?

Marvin
  • 79
  • 8
  • Does it answer your question? https://stackoverflow.com/a/1641960/1066240 – biesior Mar 01 '21 at 15:13
  • Not exactly. I believe that is just for one line. – Marvin Mar 01 '21 at 17:17
  • in such case just take width of the longest, what's the problem? – biesior Mar 01 '21 at 17:42
  • The problem is. Using the API, I just want to put in one long string (without line breaks). So the PHP system should determine how many space it has and where to break, to fit it in the image. But I don't know how. – Marvin Mar 01 '21 at 18:53
  • It's up to you, my first goal would be to make it working. You will NOT find solution that divides one sentence to lines automatically and finally will find the width of the longest line. – biesior Mar 01 '21 at 19:00

0 Answers0