Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
?>
like image 301
AlexMorley-Finch Avatar asked Dec 14 '11 10:12

AlexMorley-Finch


People also ask

How do I make a transparent PNG in HTML?

Transparency is not done in HTML, but is a part of the image itself. The browser will see the image as a PNG and display it as a PNG automatically. To add transparency to the image, you will have to edit the file with a graphics editor like Photoshop. Save this answer.


1 Answers

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

like image 184
Dejan Marjanović Avatar answered Oct 11 '22 13:10

Dejan Marjanović