imagestring

(PHP 3, PHP 4, PHP 5)

imagestring -- 水平地画一行字符串

说明

bool imagestring ( resource image, int font, int x, int y, string s, int col )

imagestring()col 颜色将字符串 s 画到 image 所代表的图像的 xy 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果 font 是 1,2,3,4 或 5,则使用内置字体。

例子 1. imagestring() 例子

<?php
// 建立一幅 100X30 的图像
$im = imagecreatetruecolor(100, 30);

// 白色背景和蓝色文本
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// 把字符串写在图像左上角
imagestring($im, 5, 0, 0, "Hello world!", $textcolor);

// 输出图像
header("Content-type: image/jpeg");
imagejpeg($im);
?>

参见 imageloadfont()imagettftext()


add a note add a note User Contributed Notes
god at in-heaven dot org
19-Oct-2006 05:47
Here's a simple function for creating an aligned string which is cutted to match the space between $x1 and $x2
<?php
function imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align="center") {
  
$fontwidth = imagefontwidth($font);
  
$fullwidth = strlen($text) * $fontwidth;
  
$maxwidth = $x2-$x1;
  
$targetwidth = $fullwidth-(4*$fontwidth);
   if(
$fullwidth > $maxwidth) {
       for(
$i = 0; $i < strlen($text) AND ((strlen($text)-($i-4))*$fontwidth) > $targetwidth ;$i++) { }
      
$text = substr($text,0,(strlen($text)-$i)-4)."...";
   }
   if(
$align == "left") imagestring($img,$font,$x1,$y,$text,$color);
   elseif(
$align == "right") imagestring($img,$font,$x2 - ((strlen($text) * $fontwidth)),$y,$text,$color);
   else
imagestring($img,$font,($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Usage:
<?php
imagestringcutted
($img,$font,$y,$x1,$x2,$text,$color,$align);
?>
Will create a string $text, which is cutted if it's too long to match between  $x1 and $2, on $img with font $font and color $color at height $y and with align to $align.
Hope it will help some people.
Sorry for my bad English.
rush at 507magazine dot com
01-Mar-2006 03:54
hello, I noticed that if you put a rand(3,5) it will put random sizes of font to each character put on the image. this is very useful when programming captchas for anti-spam form verification.
julien / at / theoconcept.com
02-Feb-2006 07:21
If you are looking for a way to generate a "CAPTCHA" image for a form verification (to verify it is not a robot), have a look at this : http://blog.theoconcept.com/static/distortion/

It gives an animated image with the parameter string, with distortion, here is an example :
http://blog.theoconcept.com/static/distortion/distortion.php

(*)  You'll need GD + Freetype support
(**) You'll need ImageMagick on the machine
m dot onderwater at esperantoxl dot nl
06-Dec-2005 02:55
There is a small error in the function for horizontal and vertical centering by "jurgen dot vanoosterwijck at pandora dot be"

the line

 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);

should be

 $cy = (imagesy($img)/2) - (imagefontheight($font)/2);
aly at slo-igre dot net
11-Jun-2005 04:12
There is an error in "tjpoe at cableaz dot com" 's function ImageStringWrap. Instead of

   else
           $string = $text;

there should be

     else
           $string = array($text);

for function to work for strings with only one word. Otherwise it works like a charm, thanks.
tjpoe at cableaz dot com
28-May-2005 10:48
i modified the centering functions and created this which centers each word on it's own line. You can adjust the spacing with the $valign var. currently no implimentation if text is too large for image. strings are tokenized by space, but can obviously be changed.

function ImageStringWrap($image, $font, $text, $color)
{
  $fontwidth = ImageFontWidth($font);
  $fontheight = ImageFontHeight($font);
  $words= str_word_count($text);
  if ($words > 1){
   $string=array(strtok($text,' '));
   for ($i = 1 ; $i <= $words ; $i++){
     $string=array_merge($string,array($i=>strtok(' ')));
   }
  }
  else
   $string=$text;
  $vspace=4;
  $y=((imagesy($image)-($fontheight*$words)-($words*$vspace))/2);
  foreach($string as $st){
   $x=((imagesx($image)-($fontwidth * strlen($st)))/2);
   ImageString($image,$font,$x,$y,$st,$color);
   $y+=($fontheight+$vspace);
  }
}
hope this is helpful
bpgordon at gmail dot com
24-May-2005 07:04
This code produces a png image of the text within the query. It autofits to the length of the string.
Usage: http://yoursite.com/text.php?abcdefg+hijk

Use + to produce a space in the image. The + can be excaped with a carat (^). Most other symbols work fine in the query string, like the ?.

<?php
header
("Content-type: image/png");
$string = $_ENV["QUERY_STRING"];
$md5 = md5($string); //just so we don't convert valid text into a +
$string = str_replace("^+", $md5, $string); //replaces ^+ with long, unnatural string
$string = str_replace("+", " ", $string); //replaces + with space
$string = str_replace($md5, "+", $string); //replaces the long, unnatural string with +
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);
$image = @imagecreate($width+2, $height+2);
$black = imagecolorallocate($image, 0, 0, 0); //background
$white = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 2, 1, 1$string, $white);
imagepng($image);
imagedestroy($image);
?>
jurgen dot vanoosterwijck at pandora dot be
13-May-2005 01:52
Based on the previous example, here's how to center a string both horizontally and vertically...

<?php
function imagestringcentered ($img,$font,$text,$color) {
 while (
strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if (
$font > 1) { $font--; }
  else { break; }
 }
 
$cy = (imagesy($img)/2) - (imagefontwidth($font)/2);
 
imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
shadikka at gmail dot com
27-Mar-2005 03:49
My version of the centered string, it decreases the font number (since I've noticed smaller numbers are smaller fonts) until 1 if the string won't fit. Then it will give up.

<?php
function imagestringcentered ($img,$font,$cy,$text,$color) {
 while (
strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if (
$font > 1) { $font--; }
  else { break; }
 } 
 
imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
webmaster at acdrifter dot com
01-Mar-2005 12:08
If you are looking to center the text, use the following function; I'm not promising perfection...

function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
   $textWidth = imagefontwidth( $font ) * strlen( $str );
   $xLoc = ( $xMax - $xMin - $textWidth ) / 2 + $xMin + $font;
   imagestring( $img, $font, $xLoc, $y, $str, $col );
}
cesargus at yahoo dot com
18-Nov-2004 02:27
//simple hello world

<?
header
("Content-type: image/png");

$img_handle = ImageCreate (200, 20) or die ("Cannot Create image");
$back_color = ImageColorAllocate ($img_handle, 0, 10, 10);
$txt_color = ImageColorAllocate ($img_handle, 235, 235, 51);
ImageString ($img_handle, 10, 25, 5"Hello world!", $txt_color);
ImagePng ($img_handle);
?>
brooks dot boyd at gmail dot com
14-Oct-2004 03:35
Drawing a string as an image is a handy way to disguise an eMail address so spam sniffers can't get it as easily. The only catch to creating a dynamic image with your eMail in it is the eMail to be displayed must be passed via the query string to enable static HTML to use it. So, the eMail must be encrypted slightly in order to not defeat the purpose of not typing your eMail address outright. I wrote the following script to do so:

Save the following as email.php
<?php
  
if ($_GET['addr'] != "") {
      
$msg = $_GET['addr'];
      
$msg = preg_replace("/\[dot]/",".",$msg);
      
$msg = preg_replace("/\[at]/","@",$msg);
      
$final = "";
       for (
$i=0; $i<=strlen($msg); $i++) {
          
$final .= substr($msg, strlen($msg)-$i, 1);
       }
      
$msg = $final;

      
$char_width = 8;
      
$char_height = 17;
      
$padding = 3;
      
$width = $padding*2+strlen($msg)*$char_width;
      
$height = +$padding*2+$char_height;
      
$im = imagecreatetruecolor($width,$height);
      
imagealphablending($im, FALSE);
      
imagesavealpha($im, TRUE);
      
$bg = imagecolorallocatealpha($im, 255, 255, 0, 100);
      
$text = imagecolorallocatealpha($im, 0, 0, 0, 0);
      
imagefilledrectangle ($im, 0, 0, $width, $height, $bg); # Make transparent
      
imagestring($im, 4, $padding, $padding, $msg, $text);
   } else {
      
$im = imagecreatetruecolor(1,1);
      
imagealphablending($im, FALSE);
      
imagesavealpha($im, TRUE);
      
$bg = imagecolorallocatealpha($im, 255, 0, 0, 125);
      
imagefilledrectangle ($im, 0, 0, 1, 1, $bg); # Make transparent
  
}
  
header('Content-type: image/jpg');
  
imagepng($im);
  
imagedestroy($im);

?>

If the script is called without an eMail address, it outputs a 2x2 transparent image.

To call the script to generate the eMail "user@home.com", the HTML tag would be:

<img src="email.php?addr=moc[dot]emoh[at]resu">

To 'encrypt' the eMail address to pass to the script, write the address backwards and replace "." with "[dot]" and "@" with "[at]". It's not the most ironclad protection, but it thwarts most casual eMail sniffers.
php dot net at mvoncken dot nl
15-Feb-2003 06:18
A simple example:
To make one line of text fit in the image.

<?php
header
("Content-type: image/png");
$string = "spam@mvoncken.nl";                                             
$font  = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0$string, $text_color);
imagepng ($im);
?>

I use something like this for spamprotection of my visitors (pass userid as an url-parameter for this php)
aholmes84 at hotmail dot com
09-Nov-2002 03:25
When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.
deejay_world at yahoo dot com
11-Jun-2002 10:25
Width ImageString, the strings you draw are not automatically wrapped width the edge of the image. You may use this function to automatically wrap them:

function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth)
{
   $fontwidth = ImageFontWidth($font);
   $fontheight = ImageFontHeight($font);

   if ($maxwidth != NULL) {
       $maxcharsperline = floor($maxwidth / $fontwidth);
       $text = wordwrap($text, $maxcharsperline, "\n", 1);
     }

   $lines = explode("\n", $text);
   while (list($numl, $line) = each($lines)) {
       ImageString($image, $font, $x, $y, $line, $color);
       $y += $fontheight;
     }
}

So, in particular, if you want to wrap a text with the edge of the Image, you may do:
ImageStringWrap($img, $font, 0, $y, $text, $color, ImageSX($img) );
bob dot brown at opus dot co dot nz
03-Apr-2002 07:59
If you find that you are getting two characters on the end of your imageString that look like a Y and an upside down L then they're probably representations of CR/LF.  Try trim()ing the string before outputting it.  (I was sooo sure this was a bug <g>)