Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Image Functions : imagestring

imagestring

Draw a string horizontally (PHP 4, PHP 5)
bool imagestring ( resource image, int font, int x, int y, string string, int color )

Draws a string at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

font

Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the upper left corner

y

y-coordinate of the upper left corner

string

The string to be written

color

A color identifier created with imagecolorallocate()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example1023.imagestring() example

<?php
// create a 100*30 image
$im = imagecreate(100, 30);

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

// write the string at the top left
imagestring($im, 5, 0, 0, "Hello world!", $textcolor);

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

The above example will output something similar to:


Related Examples ( Source code ) » imagestring









Code Examples / Notes » imagestring

deejay_world

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


aholmes84

When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.

bpgordon

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


aly

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.


m dot onderwater

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


piotr dot sulecki

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.

shadikka

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);
}
?>


bob dot brown

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

webmaster

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


julien /

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


iibm

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


tjpoe

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


gannon

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


god

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

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.

brooks dot boyd

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.


jurgen dot vanoosterwijck

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);
}
?>


php dot net

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)


cesargus

//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);
?>


jlamer

//  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);
}


Change Language


Follow Navioo On Twitter
gd_info
getimagesize
image_type_to_extension
image_type_to_mime_type
image2wbmp
imagealphablending
imageantialias
imagearc
imagechar
imagecharup
imagecolorallocate
imagecolorallocatealpha
imagecolorat
imagecolorclosest
imagecolorclosestalpha
imagecolorclosesthwb
imagecolordeallocate
imagecolorexact
imagecolorexactalpha
imagecolormatch
imagecolorresolve
imagecolorresolvealpha
imagecolorset
imagecolorsforindex
imagecolorstotal
imagecolortransparent
imageconvolution
imagecopy
imagecopymerge
imagecopymergegray
imagecopyresampled
imagecopyresized
imagecreate
imagecreatefromgd2
imagecreatefromgd2part
imagecreatefromgd
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromstring
imagecreatefromwbmp
imagecreatefromxbm
imagecreatefromxpm
imagecreatetruecolor
imagedashedline
imagedestroy
imageellipse
imagefill
imagefilledarc
imagefilledellipse
imagefilledpolygon
imagefilledrectangle
imagefilltoborder
imagefilter
imagefontheight
imagefontwidth
imageftbbox
imagefttext
imagegammacorrect
imagegd2
imagegd
imagegif
imagegrabscreen
imagegrabwindow
imageinterlace
imageistruecolor
imagejpeg
imagelayereffect
imageline
imageloadfont
imagepalettecopy
imagepng
imagepolygon
imagepsbbox
imagepsencodefont
imagepsextendfont
imagepsfreefont
imagepsloadfont
imagepsslantfont
imagepstext
imagerectangle
imagerotate
imagesavealpha
imagesetbrush
imagesetpixel
imagesetstyle
imagesetthickness
imagesettile
imagestring
imagestringup
imagesx
imagesy
imagetruecolortopalette
imagettfbbox
imagettftext
imagetypes
imagewbmp
imagexbm
iptcembed
iptcparse
jpeg2wbmp
png2wbmp
eXTReMe Tracker