Create transparent png with text from scratch in php

24.2k Views Asked by At

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);
?>
3

There are 3 best solutions below

1
Dejan Marjanović On BEST ANSWER
<?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.

0
luastoned On

Here's the solution based on your original code.

<?php
    $width = 640;
    $height = 480;
    $text = "My Text";
    $fontsize = 5;

    $img = imagecreate($width, $height);

    // Transparent background
    $black = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $black);

    // Red text
    $red = imagecolorallocate($img, 255, 0, 0);
    imagestring($img, $fontsize, 0, 0, $text, $red);

    header('Content-type: image/png');
    imagepng($img);
    imagedestroy($img);
?>
0
Arshad Jilani On

I Think GD is one of the most popular for generating images, with imagettftext.

 <?php
    $text = 'SOME TEXT';

    $font="c:/windows/Fonts/Latinwd.ttf"; //Load font file for windows

    $im = ImageCreate(700, 140);

    $bla = imagecolorallocate($im, 0, 0, 0);
    imagecolortransparent($im, $bla); //transparent background

    $black = imagecolorallocate($im, 255,255,255);
    ImageTTFText ($im, 38, 0, 10, 40, $black, $font, $text);

    header('Content-Type: image/png');
    ImagePNG($im, 'name.png');
    imagedestroy($im);
    ?>