Search code examples
phpimagepngimage.createimage

Create transparent png with text from scratch in php


All the examples I've found on the web seem to create pngs with text from an existing png. Is it possible to create a transparent png from scratch and then add text?

The code ive got so far follows (but it doesnt work. just outputs a blank image source)

<?php
    $width = 150;
    $height = 30;
    $text = "My Text";
    $fontsize = 5;

    $im = imagecreate($width, $height);
    $transcolor = imagecolortransparent($im);

    imagestring($im, $fontsize, 0, 0, $text, $transcolor);

    header('Content-type: image/png');
    imagepng($im);
    imagedestroy($im);
?>

Solution

  • <?php
        $font = 25;
        $string = 'My Text';
        $im = @imagecreatetruecolor(strlen($string) * $font / 1.5, $font);
        imagesavealpha($im, true);
        imagealphablending($im, false);
        $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
        imagefill($im, 0, 0, $white);
        $lime = imagecolorallocate($im, 204, 255, 51);
        imagettftext($im, $font, 0, 0, $font - 3, $lime, "droid_mono.ttf", $string);
        header("Content-type: image/png");
        imagepng($im);
        imagedestroy($im);
    ?>
    

    Use imagestring instead of imagettftext if you don't want custom font.