创建给定文本的透明png

I would like to create a transparent png of some given text. I don't want to specify the width and height of the image, but have it automatically size to the size of the text. I've experimented with both imagemagick and PHP, however, haven't quite got it. How would I do so using either of these technologies, or any other technology? Also, why is one technology better than the other?

imagemagick solution

Works, except requires size of image to be specified instead of automatically sizing to text size.

convert -size 560x85 xc:transparent -font Palatino-Bold -pointsize 72 -fill black -stroke red -draw "text 20,55 'Linux and Life'" linuxandlife.png

PHP Solution

Works except chops a bit off the right side. Also, if I make multiple images with text of the same font size and font type, and they all have capital letters in them, the height of the images are not all the same, yet I would have expected them to have been the same. Also, just played with image functions for the first time today, and please let me know if I am doing anything else incorrect.

<?php

    $font_size = 11;
    $angle=0;
    //$fonttype="/usr/share/fonts/liberation/LiberationMono-Regular.ttf";
    $fonttype="/usr/share/fonts/dejavu/DejaVuSans.ttf";

    $text='Some text';
    $file='MyFile.png';

    $bbox = imagettfbbox($font_size, $angle, $fonttype, $text);
    $x1 = $bbox[2] - $bbox[0];
    $y1 = $bbox[1] - $bbox[7];

    $im = @imagecreatetruecolor($x1, $y1);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $color_background = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $color_background);
    $color_text = imagecolorallocate($im, 255, 0, 0);
    imagettftext($im, $font_size, $angle, 0, $font_size, $color_text, $fonttype, $text);
    imagepng($im,$file);
    imagedestroy($im);
?>

I would choose the pure php solution, so you are not depended on external libs like imagemagick.

Maybe it wohl be a good idea if you would use browser caching, so you don`t ne to generate the images on every request.

Yust add the following code before your 'imagettfbbox' and put your image generation code in the ELSE.

$string = $text . filemtime($file);
$eTag = md5($string);
header("ETag: ".$eTag);
$httpModEtag  = !empty($_SERVER['HTTP_IF_NONE_MATCH'])? $_SERVER['HTTP_IF_NONE_MATCH']:"";
if($httpModEtag===$eTag)
{
  // tells the browser to use his cached image
  header("HTTP/1.1 304 Not Modified", true, 304);
}
else
{
  // tells the browser to refresh the cache
  header("Cache-Controll: must-revalidate");

  // ------ Place your Image Generation code here -------
}