center text in php image

0

I am trying to align to the center the description of some products that I bring from a database, which is then printed on a ticket. The chain that I bring is variable, it can have from 10 to 200 characters, for which I must save the data in a chain, and format it to be printed in 1 or more lines. I have tried with str_pad, but since the source is not monospace it does not work in most of the time, large differences are visualized. I was studying the php documentation but I do not understand it completely or I do not find it back. The code I use:

<?php
Header("Content-type: image/png");
$im = imagecreate(400,300);
$fondo=imagecolorallocate ($im, 255, 255, 110);
$gris=imagecolorallocate ($im, 160, 160,160);
$negro=imagecolorallocate ($im, 0, 0, 0);
$texto="Estosos dsdwsvwes rbbuna rbprueba de impresio Esto esrbbrrbr una prueba de impresiorbrr Esto es una prueba de impresion";
$lines1 = explode('|', wordwrap($texto, 28, '|'));
$y=150;
	foreach ($lines1 as $line1) {
		        {
		        	$line1=trim($line1);
		            $line1 = str_pad($line1, 30,"0", STR_PAD_BOTH);
		            $marco= ImageTTFBBox (24, 0, "arial.ttf", $line1);
					$x = abs(ceil(400 - ($marco[2]-$marco[0])));
					$y += 30;		            
					Imagettftext($im, 14, 0, $x, $y, $negro,"arial.ttf", $line1);
		        }		
		}

Imagepng($im);
imagedestroy($im);

Any help to align the $ text variable?

Thanks !!

    
asked by look68 20.02.2017 в 16:54
source

1 answer

1

Look with the corrections I made, you focus the texts well, I hope it's what you needed.

<?php
header("Content-type: image/png");
$im = imagecreate(400,300);
$fondo=imagecolorallocate ($im, 255, 255, 110);
$gris=imagecolorallocate ($im, 160, 160,160);
$negro=imagecolorallocate ($im, 0, 0, 0);
$texto="Estosos dsdwsvwes rbbuna rbprueba de impresio Esto esrbbrrbr una prueba de impresiorbrr Esto es una prueba de impresion";
$lines1 = explode('|', wordwrap($texto, 28, '|'));
$y=150;
    foreach ($lines1 as $line1) {
                {
                    $line1=trim($line1);
                    //$line1 = str_pad($line1, 30,"0", STR_PAD_BOTH);
                    $marco= ImageTTFBBox (14, 0, "arial.ttf", $line1);
                    $x = (400 - ($marco[2]-$marco[0])) / 2;
                    $y += 30;                   
                    Imagettftext($im, 14, 0, $x, $y, $negro,"arial", $line1);
                }       
        }

imagepng($im);
imagedestroy($im);

If what you wanted was to center the lines you had an error in the formula of the X coordinate and the str_pad is not necessary.

    
answered by 21.02.2017 / 00:26
source