Code / PHP Snippets / GD: Name on Image

  1. <?
  2. // GD Image Generator, based on Ro's work.
  3. // v0.1 Takes a name and places it on a predefined image
  4. ?>
  5. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  9. <title>Image Generator</title>
  10. </head>
  11. <body>
  12. <?
  13. // Full path to the font, preferably not relative
  14. $font = 'font.ttf';
  15. $fontSize = 18;
  16. $angle = 21.9;
  17. $centrePoint = array(178, 97); //x, y from bottom-left
  18. $colour = array(0, 0, 0, 0); //R(0-255), G(0-255), B(0-255), A(0-127) colour
  19.  
  20. if (empty($_REQUEST['text'])) {
  21.         // If no name was posted, then show the form to request input
  22.         echo "<form action="index.php" method="post">Enter your name: <input type="text" name="text" /><input type="submit" value="Generate Image" /></form>";
  23. } else {
  24.         // A name was posted so we can generate an image for the user
  25.         // basing it on the source image
  26.         $im = imagecreatefromjpeg('src.jpg');
  27.         $s = imagettfbbox($fontSize, $angle, $font, $_REQUEST['text']);
  28.  
  29.         // Work out the math angle for the name on the banner image
  30.         $width = cos(deg2rad($angle)) * ($s[2] - $s[0]);
  31.         $height = sin(deg2rad(90 - $angle)) * ($s[1] - $s[5]);
  32.        
  33.         $c = imagecolorallocatealpha($im, $colour[0], $colour[1], $colour[2], $colour[3]);
  34.        
  35.         $x = $centrePoint[0] - ($width / 2) + $s[0];
  36.         $y = $centrePoint[1] + ($height / 2) + $s[1];
  37.  
  38.         // Add the text to the image, at the correct angle, and in
  39.         // the correct colour and font
  40.         imagettftext($im, $fontSize, $angle, $x, $y, $c, $font, $_REQUEST['text']);
  41.  
  42.         // Send the image out to the browser
  43.         imagejpeg($im, 'dest.jpg');
  44.         print('<img src="dest.jpg?rand=' . rand() . '" alt="">');
  45. }
  46. ?>
  47. </body>
  48. </html>

Download as Text : January 6th, 2009