I would like to find some code which taxes a string of text and makes an image out of it using a TTF font...
I found a function that creates a border around the text, which is what I wanted:

function imagettfborder($im, $size, $angle, $x, $y, $color, $font, $text, $width) {
	// top
	imagettftext($im, $size, $angle, $x-$width, $y-$width, $color, $font, $text);
	imagettftext($im, $size, $angle, $x, $y-$width, $color, $font, $text);
	imagettftext($im, $size, $angle, $x+$width, $y-$width, $color, $font, $text);
	// bottom
	imagettftext($im, $size, $angle, $x-$width, $y+$width, $color, $font, $text);
	imagettftext($im, $size, $angle, $x, $y+$width, $color, $font, $text);
	imagettftext($im, $size, $angle, $x-$width, $y+$width, $color, $font, $text);
	// left
	imagettftext($im, $size, $angle, $x-$width, $y, $color, $font, $text);
	// right
	imagettftext($im, $size, $angle, $x+$width, $y, $color, $font, $text);
	for ($i = 1; $i < $width; $i++) {
		// top line
		imagettftext($im, $size, $angle, $x-$i, $y-$width, $color, $font, $text);
		imagettftext($im, $size, $angle, $x+$i, $y-$width, $color, $font, $text);
		// bottom line
		imagettftext($im, $size, $angle, $x-$i, $y+$width, $color, $font, $text);
		imagettftext($im, $size, $angle, $x+$i, $y+$width, $color, $font, $text);
		// left line
		imagettftext($im, $size, $angle, $x-$width, $y-$i, $color, $font, $text);
		imagettftext($im, $size, $angle, $x-$width, $y+$i, $color, $font, $text);
		// right line
		imagettftext($im, $size, $angle, $x+$width, $y-$i, $color, $font, $text);
		imagettftext($im, $size, $angle, $x+$width, $y+$i, $color, $font, $text);
	}
}

// settings
$font = 'deftone_0.ttf';
$text = 'Stridulation Records';
// image
header("Content-type: image/png");
$im = imagecreate(400, 50); 
// colors
$white = imagecolorallocate($im, 255, 255, 255);
//$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
$grey = imagecolorallocate($im, 175, 175, 175);
$blue = imagecolorallocate($im, 0, 0, 255);

// display text
imagettfborder($im, 20, 0, $border, 30, $black, $font, $text, 1);
imagettftext($im, 20, 0, $border, 30, $white, $font, $text);

// display image
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);

However when you change the color of the font the color of the entire image created by imagecreate is created.

I moved on to another function I found online:

// settings
$font = 'deftone_0.ttf';
$text = 'Stridulation Records';
// image
header("Content-type: image/png");
$im = imagecreate(200, 50); 
// colors
$white = imagecolorallocate($im, 255, 255, 255);
//$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
$grey = imagecolorallocate($im, 175, 175, 175);
$blue = imagecolorallocate($im, 0, 0, 255);

// display text
imagettfborder($im, 20, 0, $border, 30, $black, $font, $text, 1);
imagettftext($im, 20, 0, $border, 30, $white, $font, $text);

// display image
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);

/*
/**
 * Function for converting Text to Image.
 * Kip CENTURY.TTF file in same folder.
 * 
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2007/08/03
 * 
 */
     //Example call.
    $str = "New life in programming.\nNext Line of Image.\nLine Number 3\n" .
        "This is line numbet 4\nLine number 5\nYou can write as you want.";    
header("Content-type: image/gif"); imagegif(imagettfJustifytext($str,"deftone_0.ttf",2)); //End of example. /** * @name : makeImageF * * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center). * * @param String $text : String to convert into the Image. * @param String $font : Font name of the text. Kip font file in same folder. * @param int $W : Width of the Image. * @param int $H : Hight of the Image. * @param int $X : x-coordinate of the text into the image. * @param int $Y : y-coordinate of the text into the image. * @param int $fsize : Font size of text. * @param array $color : RGB color array for text color. * @param array $bgcolor : RGB color array for background. * */ function imagettfJustifytext($text, $font="arial.ttf", $Justify=2, $W=0, $H=0, $X=0, $Y=0, $fsize=22, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){ $angle = 0; $L_R_C = $Justify; $_bx = imageTTFBbox($fsize,0,$font,$text); $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W; //If Height not initialized by programmer then it will detect and assign perfect height. $H = ($H==0)?abs($_bx[5]-$_bx[3]):$H; //If Width not initialized by programmer then it will detect and assign perfect width. $im = @imagecreate($W, $H) or die("Cannot Initialize new GD image stream"); $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]); //RGB color background. $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); //RGB color text. $bg_color = imagecolorat($im,1,1); imagecolortransparent($im, $bg_color); if($L_R_C == 0){ //Justify Left imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text); }elseif($L_R_C == 1){ //Justify Right $s = split("[\n]+", $text); $__H=0; foreach($s as $key=>$val){ $_b = imageTTFBbox($fsize,0,$font,$val); $_W = abs($_b[2]-$_b[0]); //Defining the X coordinate. $_X = $W-$_W; //Defining the Y coordinate. $_H = abs($_b[5]-$_b[3]); $__H += $_H; imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val); $__H += 6; } } elseif($L_R_C == 2){ //Justify Center $s = split("[\n]+", $text); $__H=0; foreach($s as $key=>$val){ $_b = imageTTFBbox($fsize,0,$font,$val); $_W = abs($_b[2]-$_b[0]); //Defining the X coordinate. $_X = abs($W/2)-abs($_W/2); //Defining the Y coordinate. $_H = abs($_b[5]-$_b[3]); $__H += $_H; imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val); $__H += 6; } } return $im; }

but I still don't understand how I can create a transparent background AROUND the text and how I can insert this into a php page, because when I do I get the "cannot modify header information, header already sent" error.

How can I create an image with a ttf font from a text string, have a border around it and transparent background around the image and place that image in an existing page output?

Thanks a lot

    To place an image into a page you use the <img> tag. If you stop and think about how that works for a second, what you're trying to do will become apparent. The most common problem with this is that people just insert the PHP code directly into the HTML they are outputting.

    Basically, PHP is creating a virtual file, which is your image. In the same way that you wouldn't open up an image with a text editor and just paste that into your HTML code, you won't be able to do that with PHP code generating an image either. Treat the .php file creating your image as an actual image file on your server, and use it just like you would a regular .jpg for example.

    As for the transparency, I believe that you may be able to solve it by allocating another colour first, before you define white.

      are you saying that I should have this code in a separate php file and then call it like this:
      <img src="imagettftextcode.php?string=mytexthere">
      ?

        Exactly. PHP can output many different types of file (although it's usually just HTML) but it can only output one type at a time.

        You may want to add some code in your imagettftextcode.php file that checks for the referrer header (you can find this in $_SERVER) just as an added precaution to prevent people using your script to create images that they use on their own site. This is a crude attempt to stop hot-linking basically. While hot-linking isn't a huge problem unless you've got hundreds of people hot-linking your images/media in this case you've got the added burden of PHP creating the image, which uses up CPU time on the server.

        There is a final way to improve it, by adding in a server-side caching mechanism, i.e have PHP save the image the first time it creates it, and then just send the saved image back rather than re-create it each time. This makes it slightly more efficient, although if you don't expect much traffic to your site then it's probably not going to be an issue.

          However, if you are producing images with the same message over and over again, it makes far more sense to simply save those images and serve up the saved version than to recreate them every time. A simple way to do this would be to store the message in a DB along with a unique file name associated with that message. If the message you are serving up doesn't exist in the db, then you make the image, save it to file and put that info into the DB. Then whether it existed before or not, you serve up the saved file.

            Ashley Sheridan;10996823 wrote:

            PHP can output many different types of file (although it's usually just HTML) but it can only output one type at a time.

            Mostly true... PHP can simultaneously output any and all "types" of data you want. In the end, it outputs whatever you tell it to output.

            Now, whether or not the receiving side will understand that output is a whole different matter. For example, the HTTP standards dictate that you can only output a single resource per request. The "single resource" at first will be the HTML document that is to contain your PHP-generated image. In other words, it's just plain text.

            Ashley Sheridan;10996823 wrote:

            You may want to add some code in your imagettftextcode.php file that checks for the referrer header (you can find this in $_SERVER)

            Don't do this. Ever. The 'Referer' HTTP header is completely optional and can be a) disabled altogether in the user's browser configuration, or b) stripped/filtered out by intermediate proxies/gateways.

            General rule of thumb: If you don't want people stealing (or "hotlinking") your images, then don't put them on the web.

              Thanks for all your help.
              Thanks to your suggestions I got it working. Now the only thing I am left wondering is why I see a tiny but annoying white border around all my text... it becomes really obvious with solid backgrounds are you can see in my example file here:
              http://stridulationrecords.com/test.html

              Here's the code I am using:

                  $str = $_GET['text'];
                  header("Content-type: image/png");
                  imagepng(imagettfJustifytext($str,"deftone_0.ttf",2));
                  //End of example.
              
              
              /**
               * @name                    : makeImageF
               * 
               * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
               * 
               * @param String $text     : String to convert into the Image.
               * @param String $font     : Font name of the text. Keep font file in same folder.
               * @param int    $W        : Width of the Image.
               * @param int    $H        : Hight of the Image.
               * @param int    $X        : x-coordinate of the text into the image.
               * @param int    $Y        : y-coordinate of the text into the image.
               * @param int    $fsize    : Font size of text.
               * @param array  $color    : RGB color array for text color.
               * @param array  $bgcolor  : RGB color array for background.
               * 
               */
              
              
              
              function imagettfJustifytext($text, $font="arial.ttf", $Justify=2, $W=0, $H=0, $X=0, $Y=0, $fsize=24, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
              
                  $angle = 0;
                  $L_R_C = $Justify; 
                  $_bx = imageTTFBbox($fsize,0,$font,$text);
              
                  $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    //If Height not initialized by programmer then it will detect and assign perfect height. 
                  $H = ($H==0)?abs($_bx[5]-$_bx[3]):$H;    //If Width not initialized by programmer then it will detect and assign perfect width. 
              
              $im = @imagecreate($W, $H)
                      or die("Cannot Initialize new GD image stream");
              
              
                  $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);         //RGB color background.
                  $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            			//RGB color text.
                  $bg_color = imagecolorat($im,1,1);
              
              	// add this line to make the background of the text transparent
              	imagecolortransparent($im, $bg_color);
              
                  if($L_R_C == 0){ //Justify Left
              
                      imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
              
                  }elseif($L_R_C == 1){ //Justify Right
                      $s = split("[\n]+", $text);
                      $__H=0;
              
                      foreach($s as $key=>$val){
              
                          $_b = imageTTFBbox($fsize,0,$font,$val);
                          $_W = abs($_b[2]-$_b[0]); 
                          //Defining the X coordinate.
                          $_X = $W-$_W;
                          //Defining the Y coordinate.
                          $_H = abs($_b[5]-$_b[3]);  
                          $__H += $_H;              
                          imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);    
                          $__H += 6;
              
                      }
              
                  }
                  elseif($L_R_C == 2){ //Justify Center
              
                      $s = split("[\n]+", $text);
                      $__H=0;
              
                      foreach($s as $key=>$val){
              
                          $_b = imageTTFBbox($fsize,0,$font,$val);
                          $_W = abs($_b[2]-$_b[0]); 
                          //Defining the X coordinate.
                          $_X = abs($W/2)-abs($_W/2);
                          //Defining the Y coordinate.
                          $_H = abs($_b[5]-$_b[3]);  
                          $__H += $_H;     
              
                          imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $val);    
                          $__H += 6;
              
                      }
              
                  }        
              
                  return $im;
                  imagedestroy($im);
              
              }
              ?>

                Try adding this line before you write text to the image:

                imagesavealpha($im, true);
                imagealphablending($im, true);
                

                I saw it as a solution elsehwhere to a similar problem.

                  Thanks for the suggestions Ashley. Where would you put this code exactly? I tried it before imagecreate, before imagecolorallocate, before imagecolortransparent and before imagettftext and it never removed the white border...

                    any other ideas? I can't seem to get rid of those white noise borders around the font

                      Write a Reply...