10

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);
?>
AlexMorley-Finch
  • 6,785
  • 15
  • 68
  • 103

3 Answers3

21
<?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.

johnsampson
  • 376
  • 3
  • 14
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • I want to add HTML in text like: $string = '

    My Text

    '; How can I achieve this. Can you please help?
    – Ravi May 03 '22 at 11:54
5

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);
?>
luastoned
  • 663
  • 3
  • 4
0

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