Biography:

Location: Dayton, OH
College: Cedarville University, Cedarville, OH
Degree: B.A. Management Information Systems (2002)
Certifications: Microsoft Certified Professional (MCP) 2002

Interests:

Music, Playing Guitar, Working on Cars, Home Improvement, Photography, Computers, Website Programming, Driving in the snow, NHL Hockey, Sand Volleyball, Settlers of Catan board game

Favorites:

Foods: Lasagna, Carrot Casserole, Chicken Parmesan
Sports: Hockey, Football, Volleyball, Soccer
Desserts: Peanut Butter Pie, Peanut Butter Passion ice cream
TV Shows: 24, The Office, Heroes, Mythbusters, Top Gear, Fifth Gear, Modern Marvels, Seinfeld, Simpsons


Contact Me:
Use this area to send me a note or message:
Name:
Email:
Comments:
Security Code:

Fun links you should probably check out:


Fun games you might want to play:


Current Code Samples:


Future Code Samples:

  • CAPTCHA form-protection of images using PHP and GD 2.0 library
  • Resizing images using PHP and the GD 2.0 library
  • Rotating images using PHP and the GD 2.0 library
CODE TUTORIAL: Text to Image with PHP and GD 2.0 Library

Output Panel

Text to Output:
Image Width:
Image Height:
Background Color: (hex): #
Bitmap Font:
TrueType Font:
Font Size: px
Font Color: (hex) #
Show Dropshadow?
Shadow Text Color #
Shadow Text Offset
Left Offset: px
Top Offset: px
Output to Browser?
Output Filetype:
JPG Compression % Quality: % 1-100


Here is the code in PHP I've written that reads several input parameters and outputs an image:

PHP FUNCTION: textToImage()

string textToWrite    - Text output we want to write to the exported image
int width,             - Width (in px) we want the exported image to be (if not set, we'll try to auto-calculate)
int height,           - Height (in px) we want the exported image to be (if not set, we'll try to auto-calculate)
string bkndColor,     - HEX background color we want to use for the exported image
int JPGquality,       - JPG compression quality percentage (0-100)
string BitmapFont,     - Bitmap Font we want to use for the text in the exported image (1-5 are valid)
string TTFfont,       - TrueType Font we want to use for the text in the exported image (must have .ttf extension)
int TTFsize,           - Font Size (in px) we want to use for the text in the exported image
string TTFcolor,       - HEX color we want to use for the text in the exported image
int startX,           - X-axis pixel to start drawing text from (text is drawn from top to bottom)
int startY,           - Y-axis pixel to start drawing text from (text is drawn from left to right)
string imageType,     - Image MIME Type we want the exported image to be (GIF, JPG, PNG)
bool outputToBrowser  - Do we output the image as a file on the server (false), or as a graphic to the browser (true)?

PHP CODE: "text-to-image.php"
function textToImage($textToWrite, $width, $height, $bkndColor, $JPGquality=95, $BitmapFont, $TTFfont, $TTFsize=10, $TTFcolor, $shadowColor, $useTextShadow, $startX=10, $startY=10, $imageType, $outputToBrowser )
{
  //  Make sure we have been given valid $textToWrite, and that the output $width and $height are positive numbers
  if ( (strlen($textToWrite) > 0) && ($width > 0) && ($height > 0) )
  {
    //  Make sure bkndColor is not null
    if (empty($bkndColor))
    {  $bkndColor = "c9c9c9";  }
    //  Make sure TTFcolor is not null
    if (empty($TTFcolor))
    {  $TTFcolor = "000000";  }
    //  Make sure shadowColor is not null
    if (empty($shadowColor))
    {  $shadowColor = "a0a0a0";  }
    //  Make sure useTextShadow is not null
    if (empty($useTextShadow))
    {  $useTextShadow = false;  }
    
    //  Split our string into an array by line feed character
    $stringPieces = explode(chr(10), $textToWrite);
    //  Determine which line of text has the most characters
    $numChars = 0;
    foreach($stringPieces as $singleLine)
    {
      if (strlen($singleLine) > $numChars)
      {  $numChars = strlen($singleLine);  }
    }

    //  Check if the GD extension module is loaded on this webserver
    $loaded_exts = get_loaded_extensions();
    if (!in_array("gd", $loaded_exts))
    {
      die("<b>ERROR:</b><br>It appears your webserver doesn't have the GD 2.0 library installed.<br><br>Please reference <a href=\"http:// www.php.net/gd\" target=\"_blank\">http:www.php.net/gd</a> for more information on how to install this functionality.");
    }
    else
    {
      //  Collect all GD modules that are loaded
      $gd = gd_info();
      //  Check GD_Info to see if FreeType Support is enabled
      if (($gd["FreeType Support"] == 1) && ($TTFfont != ""))
      {
        //  Calculate height in pixels needed to display all of textToWrite on individual lines
        $totalTextHeight = ($startY*2) + ( count($stringPieces) * ceil($TTFsize*1.6) );
        
        //  Calculate width in pixels needed to display all of textToWrite characters from the longest line of text
        $totalTextWidth = ($startX*2) + ($numChars * 5.12 * ($TTFsize/10) );
      }
      else
      {
        if ($BitmapFont < 1)
        {  $BitmapFont = 1;  }
        if ($BitmapFont > 5)
        {  $BitmapFont = 5;  }
        
        //  Fill array with default values
        $BitmapFontHeight_arr = array("", 6, 8, 8, 10, 10);
        
        //  Calculate height in pixels needed to display all of textToWrite on individual lines
        $totalTextHeight = ($startY*2) + ( count($stringPieces) * ceil($BitmapFontHeight_arr[$BitmapFont]*1.5) );
        
        //  Fill array with default values
        $BitmapFontWidth_arr = array("", 5, 6, 7, 8, 9);
        
        //  Calculate width in pixels needed to display all of textToWrite characters from the longest line of text
        $totalTextWidth = ($startX*2) + ($numChars * $BitmapFontWidth_arr[$BitmapFont] );
      }
    
      //  If the height passed in by the user is not enough to contain the textToWrite,
      //  we will automatically resize the image so that it will be large enough
      //  to hold all of the text for display
      if ($height < $totalTextHeight)
      {  $height = $totalTextHeight;  }
      if ($width < $totalTextWidth )
      {  $width = $totalTextWidth;  }
      
      //  Create high color image by $width and $height
      $newImage = imagecreatetruecolor($width,$height);
      
      //  Create RGB color levels from bkndColor variable  
      $bkndColor = str_replace("#", "", $bkndColor); //  Remove leading #
      $redColor = hexdec(substr($bkndColor, 0, 2));
      $greenColor = hexdec(substr($bkndColor, 2, 2));
      $blueColor = hexdec(substr($bkndColor, 4, 2));  
      $bkndColor = imagecolorallocate($newImage, $redColor, $greenColor, $blueColor);
      imagefilledrectangle($newImage, 0, 0, $width, $height, $bkndColor);
      
      //  Create RGB color levels from HEX TTFcolor variable
      $TTFcolor = str_replace("#", "", $TTFcolor); //  Remove leading #
      $redColor = hexdec(substr($TTFcolor, 0, 2));
      $greenColor = hexdec(substr($TTFcolor, 2, 2));
      $blueColor = hexdec(substr($TTFcolor, 4, 2));
      $textColor = imagecolorallocate($newImage, $redColor, $greenColor, $blueColor);
      
      //  Check GD_Info to see if FreeType Support is enabled
      if (($gd["FreeType Support"] == 1) && ($TTFfont != ""))
      {
        //  Set the enviroment variable for GD
        putenv("GDFONTPATH=".realpath("."));
        $TTFfont = str_replace(".ttf", "", strtolower($TTFfont));
        
        if ($useTextShadow == true)
        {
          //  Create RGB color levels from HEX shadowColor variable
          $shadowColor = str_replace("#", "", $shadowColor); //  Remove leading #
          $redColor = hexdec(substr($shadowColor, 0, 2));
          $greenColor = hexdec(substr($shadowColor, 2, 2));
          $blueColor = hexdec(substr($shadowColor, 4, 2));
          $shadowColor = imagecolorallocate($newImage, $redColor, $greenColor, $blueColor);
          
          $shadowOffsetPX = ceil($TTFsize / 19); //  1px for every 15px of font size
          //  Add TrueType Font text shadow into image
          imagettftext($newImage, $TTFsize, 0, $startX+$shadowOffsetPX, $startY+$TTFsize+$shadowOffsetPX, $shadowColor, $TTFfont, $textToWrite);
        }
        
        //  Add TrueType Font text overlay into image
        //  array imagettftext ( resource image, float fontSize, float angle, int x, int y, int color, string fontfile, string text )
        imagettftext($newImage, $TTFsize, 0, $startX, $startY+$TTFsize, $textColor, $TTFfont, $textToWrite);
      }
      else
      {
        $startY -= 2;    
      
        if ($useTextShadow == true)
        {
          //  Create RGB color levels from HEX shadowColor variable
          $shadowColor = str_replace("#", "", $shadowColor); //  Remove leading #
          $redColor = hexdec(substr($shadowColor, 0, 2));
          $greenColor = hexdec(substr($shadowColor, 2, 2));
          $blueColor = hexdec(substr($shadowColor, 4, 2));
          $shadowColor = imagecolorallocate($newImage, $redColor, $greenColor, $blueColor);
          
          $shadowOffsetPX = 1;
          
          $loopY = $startY;
          
          //  Add plaintext shadow into image
          if (is_array($stringPieces))
          {
            foreach ($stringPieces as $item)
            {
              //  bool imagestring ( resource image, int font, int x, int y, string s, int col )
              imagestring($newImage, $BitmapFont, $startX+$shadowOffsetPX, $loopY+$shadowOffsetPX, $item, $shadowColor);
              $loopY += ceil($BitmapFontHeight_arr[$BitmapFont]*1.5);
            }
          }
          else
          {
            //  bool imagestring ( resource image, int font, int x, int y, string s, int col )
            imagestring($newImage, $BitmapFont, $startX+$shadowOffsetPX, $loopY+$shadowOffsetPX, $textToWrite, $shadowColor);
          }
        }
        
        
        //  Add plaintext overlay into image
        if (is_array($stringPieces))
        {
          foreach ($stringPieces as $item)
          {
            //  bool imagestring ( resource image, int font, int x, int y, string s, int col )
            imagestring($newImage, $BitmapFont, $startX, $startY, $item, $textColor);
            $startY += ceil($BitmapFontHeight_arr[$BitmapFont]*1.5);
          }
        }
        else
        {
          //  bool imagestring ( resource image, int font, int x, int y, string s, int col )
          imagestring($newImage, $BitmapFont, $startX, $startY, $textToWrite, $textColor);
        }
      }
  
      if ($outputToBrowser == true)
      {
        //  OUTPUT image into browser window only
        header("Content-type: image/".$imageType);
        imagepng($newImage);
      }
      else
      {  
        //  WRITE out image to file on server
        imagepng($newImage, "test.".$imageType);
        //  OUTPUT HTML for the newly created image file
        echo "<img src=\"test".$imageType."\" border=\"0\"><br>";
      }
      
      //  Destroy image variables we used in this page
      if ($newImage)
      {  @imagedestroy($newImage);  }
    }
  }
}
- Justin Tubbs