Create transparent png with text from scratch in php
Asked Answered
O

3

11

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);
?>
Obligate answered 14/12, 2011 at 10:39 Comment(1)
#6110332Iatry
F
23
<?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.

Fealty answered 14/12, 2011 at 10:42 Comment(1)
I want to add HTML in text like: $string = '<h1> My Text </h1>'; How can I achieve this. Can you please help?Therron
N
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);
?>
Normannormand answered 14/12, 2011 at 10:55 Comment(0)
B
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);
    ?>
Barometry answered 14/5, 2020 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.