For loop with imagettftext and array

2019-08-16 03:51发布

问题:

I encounter a problem while trying to make a simple text-on-image generator using PHP's GD library.

In my form page, I send variables separated by ';' to an array. And then on my image generating page, I want to display my variables from the array separately on my newly created image with a space of 15 px between them.

In my FOR loop, PHP functions should calculate the width of the display of each variable separately and the total width of the final image in order to create it.

I have tried the following code, but it doesn't works. I have alrady checked the syntax and all seems to be O.K.

Here is my code

$code = $_POST['chars'];
$size = 20;
$marge = 15;
$font = '../keyboard/NotoSans-Regular.ttf';

$text_colour = imagecolorallocate($img, 255, 255, 255);

$chars_list = trim($_POST['chars']);
$chars_array =  explode(';', $chars_list);
$count = count($chars_array);

for($i = 0; $i < $count;++$i)
{
    $box = imagettfbbox($size, 0, $font, $chars_array[$i]);
    $largeur = $box[2] - $box[0];
    $largeur_lettre = round($largeur/$count);
    $hauteur = 50;
    $img = imagecreate($largeur+$marge, $hauteur);
    $l = $chars_array[$i];
    $angle = 0;
    imagettftext($img,$size,$angle,($i*$largeur_lettre)+$marge, $hauteur, $text_colour, $font, $l);
}
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

I have tried with the following value entered in my form "ą;ć;ę;ł;ń;ó;ś;ź;ż;Ą;Ć;Ę;Ł;Ń;Ó;Ś;Ź;Ż"

Thanks in advance for your answers.

edit

The image generation function doesn't works. I get only a black page without anything. I expect an image with white background and with my letters on it.

edit 2

I have improved my code and I get a better result. This code generates an image where there is a lot of characters like é instead of ąćęłńóśźż.

I think that the problem is in my "for" loop.

As a result I expect an image with "ąćęłńóśźż" instead of é-like characters. Here is my improved code

$mot = utf8_encode('ąćęłńóśźż');

$size = 20;
$marge = 15;
$font = '../keyboard/NotoSans-Regular.ttf';

$box = imagettfbbox($size, 0, $font, $mot);
$largeur = $box[2] - $box[0];
$hauteur = $box[1] - $box[7];
$largeur_lettre = round($largeur/strlen($mot));

$img = imagecreate($largeur+$marge, $hauteur+$marge);
$blanc = imagecolorallocate($img, 255, 255, 255); 
$noir = imagecolorallocate($img, 0, 0, 0);


for($i = 0; $i < strlen($mot);++$i)
{
    $l = $mot[$i];
    $angle = mt_rand(-35,35);
    imagettftext($img,$size,$angle,($i*$largeur_lettre)+$marge, 
    $hauteur+mt_rand(0,$marge/2),$noir, $font, $l); 
}

header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

This is the result I get this result I expect as result the same image, but with ąćęłńóśźż characters instead of é.