GD and Image 函数
在线手册:中文  英文

imagestring

(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,则使用内置字体。

Example #1 imagestring() 例子

<?php
// 建立一幅 100X30 的图像
$im imagecreate(10030);

// 白色背景和蓝色文本
$bg imagecolorallocate($im255255255);
$textcolor imagecolorallocate($im00255);

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

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

参见 imageloadfont()imagettftext()


GD and Image 函数
在线手册:中文  英文

用户评论:

Dirkjan (2009-10-28 07:02:37)

I created this very simple function to place text in the horizontal center of an image.

image = the image.
image_width = the width of the image.
string = the text you want to add.
font_size = font size, between 1 and 5.
y = vertical position of the text.
color = the color of the text

<?php
//place text in the center of the image
function CenterImageString($image$image_width$string$font_size$y$color)
 {
 
$text_width imagefontwidth($font_size)*strlen($string);
 
$center ceil($image_width 2);
 
$x $center - (ceil($text_width/2));
 
ImageString($image$font_size$x$y$string$color);
 }
?>

To use the function in your script, you can do like this:

<?php
header
("Content-type: image/png");
$picture imagecreate(100,100);
$black ImageColorAllocate ($picture000);
CenterImageString($picture100"Centered text"245$black);
ImagePng ($picture);
?>

jordanslost at gmail (2009-09-04 16:52:27)

Here is a small bit I made for writing to a image from right to left when you are limited to imagestring()

<?php

        $pageview_letters 
preg_split('//'$string, -); // Form are original array of letters.
        
$minus 6// The letter spacing in pixels
        
$first true// Whether or not we have started the string
        
$x 375// X Location of imagestring
        
$y 23// Y Location of imagestring
        
$letters = array(); // Initiate the array o letters.

        
foreach ( $pageview_letters as $letter ) {
        
            
$letters[] = $letter;
            
        }
        
        
$letters array_reverse$letters );
        
        foreach ( 
$letters as $letter ) {
        
            if ( 
$first ) {
            
                
imagestring$image2$x$y$letter$light_blue );
                
$first false;
                
            } else {
                
                
$x = ( $x $minus );
                
imagestring$image2$x$y$letter$light_blue );
                
            }
        
        }
?>

eric dot brison at anakeen dot com (2009-04-24 00:51:47)

Same function as above but it can display multi-line strings.
<?php
function sendimagetext($text) {
  
// Set font size
  
$font_size 4;

  
$ts=explode("\n",$text);
  
$width=0;
  foreach (
$ts as $k=>$string) { //compute width
    
$width=max($width,strlen($string));
  }

  
// Create image width dependant on width of the string
  
$width  imagefontwidth($font_size)*$width;
  
// Set height to that of the font
  
$height imagefontheight($font_size)*count($ts);
  
$el=imagefontheight($font_size);
  
$em=imagefontwidth($font_size);
  
// Create the image pallette
  
$img imagecreatetruecolor($width,$height);
  
// Dark red background
  
$bg imagecolorallocate($img0xAA0x000x00);
  
imagefilledrectangle($img00,$width ,$height $bg);
  
// White font color
  
$color imagecolorallocate($img255255255);

  foreach (
$ts as $k=>$string) {
    
// Length of the string
    
$len strlen($string);
    
// Y-coordinate of character, X changes, Y is static
    
$ypos 0;
    
// Loop through the string
    
for($i=0;$i<$len;$i++){
      
// Position of the character horizontally
      
$xpos $i $em;
      
$ypos $k $el;
      
// Draw character
      
imagechar($img$font_size$xpos$ypos$string$color);
      
// Remove character from string
      
$string substr($string1);      
    }
  }
  
// Return the image
  
header("Content-Type: image/png");
  
imagepng($img);
  
// Remove image
  
imagedestroy($img);
}
?>

mike at mike-griffiths dot co dot uk (2008-12-19 12:07:56)

I created an alternative using the function imagechar to create a string of an image.  The below function below was used to create an image the same height and width of the text string.  It is used on my website to mask users email addresses.

<?PHP

// Set your string somehow
$string 'your@example.com';

// Set font size
$font_size 4;

// Create image width dependant on width of the string
$width  imagefontwidth($font_size)*strlen($string);
// Set height to that of the font
$height imagefontheight($font_size);
// Create the image pallette
$img imagecreate($width,$height);
// Grey background
$bg    imagecolorallocate($img252525);
// White font color
$color imagecolorallocate($img255255255);
// Length of the string
$len strlen($string);
// Y-coordinate of character, X changes, Y is static
$ypos 0;
// Loop through the string
for($i=0;$i<$len;$i++){
    
// Position of the character horizontally
    
$xpos $i imagefontwidth($font_size);
    
// Draw character
    
imagechar($img$font_size$xpos$ypos$string$color);
    
// Remove character from string
    
$string substr($string1);    
    
}
// Return the image
header("Content-Type: image/gif");
imagegif($img);
// Remove image 
imagedestroy($img);

?>

keksnicoh at googlemail dot com (2008-11-02 10:42:17)

Some fun with imagestring:

This function is a product of too much time..
It opens an image and create a new image with one letter instead of a pixel.

<?php
error_reporting
(E_ALL);
/**
 * generates a image with chars instead of pixels
 *
 * @param string $url Filepath or url
 * @param string $chars The chars which should replace the pixels
 * @param int $shrpns Sharpness (2 = every second pixel, 1 = every pixel ... )
 * @param int $size 
 * @param int $weight font-weight/size
 * @return sesource
 * @author Nicolas 'KeksNicoh' Heimann <www.salamipla.net>
 * @date 02nov08
 */
function pixelfuck($url$chars='ewk34543§G§$§$Tg34g4g'$shrpns=1$size=4,$weight=2)
{
    list(
$w$h$type) = getimagesize($url);
    
$resource imagecreatefromstring(file_get_contents($url));
    
$img imagecreatetruecolor($w*$size,$h*$size);

    
$cc strlen($chars);
    for(
$y=0;$y <$h;$y+=$shrpns
        for(
$x=0;$x <$w;$x+=$shrpns)
            
imagestring($img,$weight,$x*$size,$y*$size$chars{@++$p%$cc}, imagecolorat($resource$x$y));
    return 
$img;
}

$url 'http://upload.wikimedia.org/wikipedia/commons/b/be/Manga_Icon.png';
$text 'I-dont-like-manga-...-Why-do-they-have-such-big-eyes? Strange-...-WHAT-WANT-YOU-DO?';

Header('Content-Type: image/png');
imagepng(pixelfuck($url$text16));
?>

Have fun  :)

Abubaker dot shamlan at gmail dot com (2008-08-19 15:02:07)

this is a function that is based on imagestring but it produces text in the center of an image i hope it helps :D

<?php
function ImageStringCenter($image_resource$font_size$line_number$total_lines$text$color ) {

    
$center_x ceil( ( imagesx($image_resource) - ( ImageFontWidth($font_size) * strlen($text) ) ) / );

    
$center_y ceil( ( ( imagesy($image_resource) - ( ImageFontHeight($font_size) * $total_lines ) ) / 2)  + ( ($line_number-1) * ImageFontHeight($font_size) ) );

ImageString($image_resource$font_size$center_x$center_y$text$color );

}
?>

mustafa at hafunny dot info (2008-08-14 02:42:53)

If you have any problem with CentralEurope's words, for example : ??????áíéú?ň??, I am try this problem by iconv() function.

<?php
// create example image
$im imagecreate(20020);
$bg imagecolorallocate($im255255255);
$textcolor imagecolorallocate($im00255);
$text "??????áíéú?ň??...";

//simple convert string
$string iconv("Windows-1250""Latin2"$text);

// write converted string at the top left
imagestring($im400$string$textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?>

sk89q (2008-03-14 14:10:47)

Creates a box of text. Has horizontal and vertical alignment, box arguments, and custom leading. I submitted this to the manual in 2003 actually, but it disappeared after a year or so (not sure why). Here it is again.

<?php
define
("ALIGN_LEFT""left");
define("ALIGN_CENTER""center");
define("ALIGN_RIGHT""right");
define("VALIGN_TOP""top");
define("VALIGN_MIDDLE""middle");
define("VALIGN_BOTTOM""bottom");

function 
imagestringbox(&$image$font$left$top$right$bottom$align$valign$leading$text$color)
{
   
// Get size of box
   
$height $bottom $top;
   
$width $right $left;
  
   
// Break the text into lines, and into an array
   
$lines wordwrap($textfloor($width imagefontwidth($font)), "\n"true);
   
$lines explode("\n"$lines);
  
   
// Other important numbers
   
$line_height imagefontheight($font) + $leading;
   
$line_count floor($height $line_height);
   
$line_count = ($line_count count($lines)) ? (count($lines)) : ($line_count);
  
   
// Loop through lines
   
for ($i 0$i $line_count$i++)
   {
       
// Vertical Align
       
switch($valign)
       {
           case 
VALIGN_TOP// Top
               
$y $top + ($i $line_height);
               break;
           case 
VALIGN_MIDDLE// Middle
               
$y $top + (($height - ($line_count $line_height)) / 2) + ($i $line_height);
               break;
           case 
VALIGN_BOTTOM// Bottom
               
$y = ($top $height) - ($line_count $line_height) + ($i $line_height);
               break;
           default:
               return 
false;
       }
      
       
// Horizontal Align
       
$line_width strlen($lines[$i]) * imagefontwidth($font);
       switch(
$align)
       {
           case 
ALIGN_LEFT// Left
               
$x $left;
               break;
           case 
ALIGN_CENTER// Center
               
$x $left + (($width $line_width) / 2);
               break;
           case 
ALIGN_RIGHT// Right
               
$x $left + ($width $line_width);
               break;
           default:
               return 
false;
       }
      
       
// Draw
       
imagestring($image$font$x$y$lines[$i], $color);
   }
  
   return 
true;
}
?>

Tobias (2008-01-17 01:40:17)

I've taken the code of Epidemiah and improved the code so that the function now can handle generic position commands (as e.g. left / bottom) or int-values as left/top position of the text to write (with positive values used as left/top position and negative from right/bottom).

So e.g. imageWriteString($img, $font, $text, $color, -10,-10); writes the text so that there is 10 px space to right and bottom border of image.

Hope this is useful. Could be optimized and checked in detail, but works fine for me.

Tobias

<?php

/**
 * write text at a specified position of the image
 * @source: http://de.php.net/manual/en/function.imagestring.php#80186
 *
 * @param &$img; reference to image
 * @param $font font to use
 * @param $text text to write
 * @param $color color to use
 * @param $position_x var if numeric: write starting at position x (if x >= 0), otherwise from right border; possible string values: left(5px from left border), right(5px from right border), center(default)
 * @param $position_y var if numeric: write starting at position y (if y >= 0), otherwise from bottom; possible string values: top(5px from top border), bottom(5px from bottom border), center(default)
 * @return void
 */
function imageWriteString(&$img$font$text$color$position_x 'center'$position_y 'center') {
    
// initialize internal variables
    
$x null;
    
$y null;

    if(
$font || $font 5){ $font 0; }
    
$num = array(array(4.66),
                 array(
4.66),
                 array(
5.612),
                 array(
6.512),
                 array(
7.616),
                 array(
8.516));

    
$width ceil(strlen($text) * $num[$font][0]);
    
$height $num[$font][1] + 2;

    
// handle position x
    
if (is_string($position_x)) {
        switch(
$position_x) {
            case 
'left':
                
$position_x 5;
                break;
            case 
'right':
                
$position_x = -5;
                break;
            default:
            case 
'center':
                
$x     = (imagesx($img) - $width 8) / 2;
                break;
        }
    }
    if (!isset(
$x)) {
        if(
is_numeric($position_x)) {
            if (
$position_x >= 0) {
                
$x $position_x// left
            
} else {
                
$x imagesx($img) - $width $position_x 8// right
            
}
        } else {
            
$x     = (imagesx($img) - $width 8) / 2// default / error value: center
        
}
    }

    
// handle position y
    
if (is_string($position_y)) {
        switch(
$position_y) {
            case 
'top':
                
$position_y 5;
                break;
            case 
'bottom':
                
$position_y = -5;
                break;
            default:
            case 
'center':
                
$y     = (Imagesy($img) - ($num[$font][1] + 2))/2;
                break;
        }
    }
    if (!isset(
$y)) {
        if (
is_numeric($position_y)) {
            if (
$position_y >= 0) {
                
$y $position_y// top
            
} else {
                
$y Imagesy($img) - $height $position_y// bottom
            
}
        } else {
            
$y     = (Imagesy($img) - ($num[$font][1] + 2))/2// default / error value: center
        
}
    }
    
imagestring($img$font$x$y$text$color);
}
?>

eviloverlord+php at gmail dot com (2008-01-03 15:28:40)

Simple script to convert a string (such as an email addresses) to a transparent image.

Usage: 
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>">

From a spambot's point of view, they see:
<img src="stringtoimg.php?string=ZpbXZG92ZXJsb3JkQGdtYWlsLmNvbQ%3D%3D">

Optional parameters:
    font_size: 1 to 5, with the default at 3
    R/G/B: the font color, in hex.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>&font_size=4&R=FF&G=FF&B=00">

<?php
/*
Filename: stringtoimg.php

Parameters:
        string: the string to print
        font_size (optional): the size of the font from 1-5
        R/G/B (optional): the RGB colors of the font in hex       
*/

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

//Get string info
$font_size = isset($_GET['font_size']) ? $_GET['font_size'] : 3;
$string urldecode(base64_decode($_GET['string']));

//Get the size of the string
$width imagefontwidth($font_size) * strlen($string);
$height imagefontheight($font_size);

//Create the image
$img = @imagecreatetruecolor($width$height)
      or die(
"Cannot Initialize new GD image stream");

//Make it transparent
imagesavealpha($imgtrue);
$trans_colour imagecolorallocatealpha($img000127);
imagefill($img00$trans_colour);

//Get the text color
$text_color = isset($_GET['R'], $_GET['G'], $_GET['B']) ?
        
imagecolorallocate($imghexdec($_GET['R']), hexdec($_GET['G']), hexdec($_GET['B'])) :
        
imagecolorallocate($img000);

//Draw the string
imagestring($img$font_size00,  $string$text_color);

//Output the image
imagepng($img);
imagedestroy($img);
?>

Epidemiah (2008-01-03 05:06:11)

Its just an easy function to write an string in the middle of a picture.

<?php

function imageCenterString(&$img$font$text$color)
{
    if(
$font || $font 5){ $font 0; }
    
$num = array(array(4.66),
                 array(
4.66),
                 array(
5.612),
                 array(
6.512),
                 array(
7.616),
                 array(
8.516));
    
$width ceil(strlen($text) * $num[$font][0]);
    
$x     imagesx($img) - $width 8;
    
$y     Imagesy($img) - ($num[$font][1] + 2);
    
imagestring($img$font$x/2$y/2$text$color);
}

?>

jlamer (2007-02-18 18:00:18)

// Example of use...
// This is a simple function to output text to an image
// which is centered (as much as I want to do by eye)
// and wrapped
// Just remember that all the sizes are guessed
// doesn't cut on the space (only on number of characters)
// or change color of text, but this isn't for that...
function imageCenterString( $imgw, $imgh,
$image_text = '', $text_size=5 )
{
$im = imagecreate( $imgw, $imgh );

// white background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 0);

$t_h = $t_w = $t_x = $t_y = 0;
$base_w =9; $base_h = 16;
$m = 0.88;
switch ( $text_size )
{
case 1: $t_w = $base_w*pow(($m*.98),4);
$t_h = $base_h*pow(($m*.98),4);
break;
case 2: $t_w = $base_w*pow($m,3);
$t_h = $base_h*pow($m,3);
break;
case 3: $t_w = $base_w*pow($m,2);
$t_h = $base_h*pow($m,2);
break;
case 4: $t_w = $base_w*$m;
$t_h = $base_h*$m;
break;
case 5: $t_w = $base_w;
$t_h = $base_h;
break;
default:
if ( $text_size >= 5 ) // set to 5
{ $t_w = $base_w; $t_h = $base_h; }
if ( $text_size < 5 ) // set to 1
{
$t_w = $base_w*pow(($m*.98),4);
$t_h = $base_h*pow(($m*.98),4);
}
break;
}

$text_array = array();

$max = floor($imgw/$t_w);

for( $i=0; strlen($image_text) > 0; $i += $max)
{
array_push($text_array, substr($image_text,0,$max));
if ( strlen($image_text) >= $max )
{ $image_text = substr($image_text,$max); }
else
{ $image_text = ''; }
}

$t_y = ($imgh/2) - ($t_h*count($text_array)/2);
foreach ( $text_array as $text )
{
$t_x = ($imgw/2)-($t_w*strlen($text)/2);
imagestring($im, $text_size, $t_x, $t_y,
$text, $textcolor);
$t_y += $t_h;
}
// output the image
header("Content-type: image/gpeg");
imagejpeg($im);
}

gannon (at) portablesofdoom (dot) org (2006-12-27 18:53:42)

I like this better than "tjpoe at cableaz dot com"'s function for wrapping text to fit width (auto-adjusts height as needed) since it doesn't only do 1 word per line.
function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
if (strlen($color) != 6) $color = 000000;
$int = hexdec($color);
$h = imagefontheight($font);
$fw = imagefontwidth($font);
$txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
$lines = count($txt);
$im = imagecreate($w, (($h * $lines) + ($lines * $space)));
$bg = imagecolorallocate($im, 255, 255, 255);
$color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
$y = 0;
foreach ($txt as $text) {
$x = (($w - ($fw * strlen($text))) / 2);
imagestring($im, $font, $x, $y, $text, $color);
$y += ($h + $space);
}
header('Content-type: image/jpeg');
die(imagejpeg($im));
}

iibm at free dot fr (2006-12-14 02:21:50)

I've made a little modification of the (quite usefull) imagestringcutted function (when align=center, it doesn't work well for me if x1!=0) so juste replace the last line with :

<?php
   
[...]
   else 
imagestring($img,$font,$x1+($x2-$x1)/ strlen($text) * $fontwidth 2,$y,$text,$color);
}
?>

Piotr dot Sulecki at traxelektronik dot pl (2006-11-09 03:18:55)

The built-in fonts used to be in latin-2 (iso8859-2) encoding. For some time, they are in latin-1 (iso8859-1) encoding. There is no way to change the encoding at all. If you need to use any other encoding, you have to use TrueType fonts.

god at in-heaven dot org (2006-10-18 14:47:37)

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)/ 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 (2006-02-28 11:54:34)

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 (2006-02-01 15:21:44)

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 (2005-12-05 10:55:30)

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 (2005-06-11 01:12:39)

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 (2005-05-27 19:48:15)

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 (2005-05-23 16:04:12)

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($image000); //background
$white imagecolorallocate($image255255255);
imagestring($image211,  $string$white);
imagepng($image);
imagedestroy($image);
?>

jurgen dot vanoosterwijck at pandora dot be (2005-05-12 10:52:58)

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) / strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>

shadikka at gmail dot com (2005-03-26 11:49:10)

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) / strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>

webmaster at acdrifter dot com (2005-02-28 20:08:52)

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 (2004-11-17 10:27:03)

//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 (2004-10-13 12:35:07)

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($msgstrlen($msg)-$i1);
        }
        
$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($imFALSE);
        
imagesavealpha($imTRUE);
        
$bg imagecolorallocatealpha($im2552550100);
        
$text imagecolorallocatealpha($im0000);
        
imagefilledrectangle ($im00$width$height$bg); # Make transparent
        
imagestring($im4$padding$padding$msg$text);
    } else {
        
$im imagecreatetruecolor(1,1);
        
imagealphablending($imFALSE);
        
imagesavealpha($imTRUE);
        
$bg imagecolorallocatealpha($im25500125);
        
imagefilledrectangle ($im0011$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 (2003-02-14 14:18:42)

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 ($im255255255); //white background
$text_color imagecolorallocate ($im00,0);//black text
imagestring ($im$font00,  $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 (2002-11-08 11:25:06)

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 (2002-06-10 19:25:28)

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 (2002-04-02 15:59:44)

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>)

易百教程