1
votes

This is what i got when I try to generate image from PHP using imagetfftext. imagestring work very well but imagetfftext.

Php generate image but text

this is my some codes.

// Dimensions
$getsize    = isset($_GET['size']) ? $_GET['size'] : '100x100';
$dimensions = explode('x', $getsize);
// Create image
$image      = imagecreate($dimensions[0], $dimensions[1]);
// Colours
$bg         = isset($_GET['bg']) ? $_GET['bg'] : 'ccc';
$bg         = hex2rgb($bg);
$setbg      = imagecolorallocate($image, $bg['r'], $bg['g'], $bg['b']);
$fg         = isset($_GET['fg']) ? $_GET['fg'] : '555';
$fg         = hex2rgb($fg);
$setfg      = imagecolorallocate($image, $fg['r'], $fg['g'], $fg['b']);
// Text
$text       = isset($_GET['text']) ? strip_tags($_GET['text']) : $getsize;
$text       = str_replace('+', ' ', $text);
// Text positioning
$fontsize   = 4;
$fontwidth  = imagefontwidth($fontsize);    // width of a character
$fontheight = imagefontheight($fontsize);   // height of a character
$length     = strlen($text);                // number of characters
$textwidth  = $length * $fontwidth;         // text width
$xpos       = (imagesx($image) - $textwidth) / 2;
$ypos       = (imagesy($image) - $fontheight) / 2;

// Generate text
//imagestring($image, $fontsize, $xpos, $ypos, $text, $setfg);
imagettftext($image, 10, 0, 50, 50,$setfg,'glyphicons-halflings-regular.ttf', $text);
imagepng($image);

Edit: this is my hex2rgb

function hex2rgb($colour)
{
    $colour = preg_replace("/[^abcdef0-9]/i", "", $colour);
    if (strlen($colour) == 6)
    {
        list($r, $g, $b) = str_split($colour, 2);
        return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b));
    }
    elseif (strlen($colour) == 3)
    {
        list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
        return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b));
    }
    return false;
}
is the font glyphicons-halflings-regular.ttf available on the system in the same directory? Please include the hex2rgb function too - Professor Abronsius
With a different font your code more or less works ( you need to include header('Content-Type: image/png'); before outputting image ) but that particular font was causing the same display problem for me in test - Professor Abronsius
@RamRaider Yes the font file is in the same folder as .php file. I just edited my post for hex2rgb function. Thanks. - Aekkawat Prommana
i think that the font is the problem, not the php code - Professor Abronsius
Ok. I found the solution. I've changed my font and it works! Thanks to @RamRaider. - Aekkawat Prommana