Webmaster-Showcase.net Creating .png Files

PHP has some nice graphics capabilities. I have used just a few to create ".png" files to be used as buttons. You may find all of the GD functions at http://www.php.net/manual/en/ref.image.php. The original GD package included ".gif" support but that was withdrawn when Unisys decided to ask for a royalty for use of its patented file format. The ".png" format was then created and released to public domain. It's actually a more compact format than ".gif". Its biggest problem is that it is newer so older browsers don't support it. As long as you put "alt" text in the img tags, this is not a big problem. Most browsers support ".png" today.

The Yahoo! WebHosting implementation of this package does not include support for TrueType or PostScript fonts. It only supports the built-in bit-mapped font format.

I created a stand-alone script to create the buttons. The script must be invoked with "?s=[words to show on button]" at the end of the URL. You may also optionally supply a color for the characters on the button using &c=rrggbb codes. (See colors.php for some color samples.) For example, this will create a button that says "next" using red characters:

http://webmaster-showcase.net/php/string2png.php?s=next&c=ff0000

The script that generates these buttons is shown here:


<html>
<head>
  <title>Create PNG from String</title>
</head>
<body>
<!-- this must be invoked with ?s=[string] in URL -->
<!-- may include &c=rrggbb for the color of the font -->
<?php

function makeapng($string, $r, $g, $b) {
  
$name = urlencode($string);
  
$filename = "$name.png";

    
$font = 7;
    
$charheight = ImageFontHeight($font);
    
$charwidth = ImageFontWidth($font);
    
$width = 2 + strlen($string) * $charwidth;
    
$height = 4 + $charheight;
    
$xloc = 2;
    
$yloc = 2;
    
$im = @ImageCreate ($width, $height) or die ("Cannot Initialize new GD image stream");
    
$background_color = ImageColorAllocate ($im, 255, 255, 255);
    
$text_color = ImageColorAllocate ($im, $r, $g, $b);
    
$trans = ImageColorTransparent($im,$background_color);
    
ImageString ($im, $font, $yloc, $xloc, $string, $text_color);
    
ImagePng ($im, $filename);

  return
$filename;
}
if (
strlen($s) < 1) {
  print
"Please supply a string value (?s=string)<br>";
} else {
  if (
strlen($c) != 6) {
    
$c= "a0a0a0";
  }
  
$allc = hexdec($c);
  
$b = $allc % 256;
  
$allc = floor($allc/256);
  
$g = $allc % 256;
  
$r = floor($allc/256);  
  
$result = makeapng($s,$r,$g,$b);
  print
"\"$s\" rendered with color r=$r, g=$g, b=$b";
  print
" on a transparent background<br />->";
  print
"<img src=\"$result\" alt=\"$s\"><-";
}
?>

Home
Show Me How Feedback
Last updated: Fri Nov 8 22:40:13 2002