Search code examples
phppnggdtruetypeimagettftext

Letter 'j' bugged with imagettftext function


I've created a script to generate an avatar by using PHP and all work fine but when there is the letter j in $data1['username'], the letter erase a part of the previous letter. NOTE : I use calibri bold italic (Downloaded here) This is my code :

$image = imagecreatefrompng("avatar.png");
    $couleur = imagecolorallocate($image, 0, 0, 0);
    $largeur_source = imagesx($image); 
    $fontfile = 'calibri.ttf';
    $angle = 0;
    $police = 18;
    $text_size = imagettfbbox($police, $angle, $fontfile, 'Hub de '.$data2['nom']); 
    $text_size2 = imagettfbbox($police, $angle, $fontfile, $data1['username']); 
    $text_width = (($text_size[2] + $text_size[4]) / 2) - (($text_size[0] + $text_size[6]) / 2);
    $text_width2 = (($text_size2[2] + $text_size2[4]) / 2) - (($text_size2[0] + $text_size2[6]) / 2);
    $x = ($largeur_source - $text_width)/2;
    $x2 = (176 - $text_width2)/2 + 74;
    //imagestring($image, $police, $x, $y, $texte_a_ecrire, $couleur);
    imagettftext($image, $police, $angle, $x2, 175, $couleur, $fontfile, $data1['username']);
    imagettftext($image, $police, $angle, $x, 35, $couleur, $fontfile, 'Hub de '.$data2['nom']);
    imagepng($image); 

When $data1['username'] = 'Paj46 the string looks like : Script's return


Solution

  • Looks like your font has no kerning pairs table

    look here for Kerning

    • you have to calculate on integers dont use x/2 direct round up .. ceil()
    • if you have the width of image in $largeur_source use it !
    • use result[2] or result[4] from imagettfbbox() to calculate. (values are the same)

    <?php
        $image = imagecreatefrompng("avatar.png");
        $couleur = imagecolorallocate($image, 0, 0, 0);
        $largeur_source = imagesx($image); 
        $fontfile = '59250___.TTF';
        $angle = 0;
        $police = 24;
        $text_size = imagettfbbox($police, $angle, $fontfile, 'Hub de' ); 
        $text_size2 = imagettfbbox($police, $angle, $fontfile, 'username'); 
        $x  = ceil(($largeur_source - $text_size[2])  / 2);
        $x2 = ceil(($largeur_source - $text_size2[2]) / 2);
        imagettftext($image, $police, $angle, $x2, 80, $couleur, $fontfile, 'username');
        imagettftext($image, $police, $angle, $x, 35, $couleur, $fontfile, 'Hub de ');
        imagepng($image); 
    

    enter image description here