Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 17
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Po wysłaniu do Dariusza problemu jeszcze nie opisanego w poradach, odpowiedź pojawia się na stronach już po 24 godzinach. To jedna z najważniejszych zalet serwisu! Za około 100 złotych rocznie mam profesjonalnego i doświadczonego konsultanta od technologii internetowych! Polecam serwis z poradami każdemu webmasterowi, niezależnie od stażu pracy i umiejętności.

Paweł Kowalski
grupa hiperMEDIA.pl

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

imagettftext

(PHP 3, PHP 4, PHP 5)

imagettftext -- Write text to the image using TrueType fonts

Description

array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )

image

The image resource. See imagecreate().

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

The text string.

May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. Strings in UTF-8 encoding can be passed directly.

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

imagettftext() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally.

Przykład 1. imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

<?php
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreate(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

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

This function requires both the GD library and the FreeType library.

See also imagettfbbox().




User Contributed Notes

--Colibri--
28-Jan-2006 09:53

If you have configured and compiled PHP with all the necessary command-line options and still get the error:

Fatal error: Call to undefined function imagettftext()

Try doing a "make clean"  before building the php apache module:

./configure [...]
make clean
make
make install

This may solve your problem (and hopefully keep you from wasting hours trying different compile options!)


nospam at nospam dot nospam
23-Jan-2006 12:51

I've found that upsampling your text by a factor of 8 or more can really improve the readability of generated text, especially in smaller font sizes (9 or less). I find it also helps with fonts that have kerning to reduce space between letters such as capital T and capital A (TA) where the top-right of the T will be cut off due to GD "features".

I can't tell you, the reader, exactly how to do this, as it will depend on how you are currently generating your text, but essentially what you want to try doing is upsize your font by a factor of 8 and then scale down the resulting image by the same factor.

So if you were using font size 10, use font size 80 and use imagecopyresampled() to divide the width/height down again by 8. The resulting image will be a few pixels different in width / height compared to direct text writing, so make sure to check your image sizes if you are using fixed dimensions.

Play around with other factors, 16 is a bit nicer but results in a higher CPU/RAM load when processing. Any higher is unnecessary I think. If possible you should also cache the image to a file instead of reprocessing it each request.


Mer`Zikain
10-Jan-2006 09:41

I was looking for a way to add kerning to my text and finally just made this function to do it. Of course, if you're generating the size of the image based on the text you're putting in it, you'll have to figure out the new size to fit the new text width but I'm sure you can figure that out.

for($i=0;$i<strlen($text);$i++){
       // Get single character
   $value=substr($text,$i,1);
   if($pval){ // check for existing previous character
       list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font,$pval);
       $nxpos+=$rx+3;
   }else{
       $nxpos=0;
   }
       // Add the letter to the image
   imagettftext($im, $fontsize, 0, $nxpos, $ypos, $fontcolor, $font, $value);
   $pval=$value; // save current character for next loop
}


webmaster at oxygenws dot com
18-Dec-2005 11:28

Developers who want to write Persian(Farsi) or Arabic characters to the image can use the following function.
http://developer.berlios.de/projects/persian-log2vis/


a4W
23-Oct-2005 09:28

This function will make your text bold:
<?php
function drawboldtext($image, $size, $angle, $x_cord, $y_cord, $r, $g, $b, $fontfile, $text)
{
  
$color = ImageColorAllocate($image, $r, $g, $b);
  
$_x = array(1, 0, 1, 0, -1, -1, 1, 0, -1);
  
$_y = array(0, -1, -1, 0, 0, -1, 1, 1, 1);
   for(
$n=0;$n<=8;$n++)
   {
    
ImageTTFText($image, $size, $angle, $x_cord+$_x[$n], $y_cord+$_y[$n], $color, $fontfile, $text);
   }
}
?>


limalopex.eisfux.de
03-Oct-2005 06:17

If you have problems displaying german umlauts or other chars with an ascii value > 127, try to convert the text-parameter first. The following function converts character-values > 127 (both: UTF-8 + ANSI) to HTML's numeric coded entities:

<?php
define
('EMPTY_STRING', '');

function
foxy_utf8_to_nce(
 
$utf = EMPTY_STRING
) {
  if(
$utf == EMPTY_STRING) return($utf);

 
$max_count = 5; // flag-bits in $max_mark ( 1111 1000 == 5 times 1)
 
$max_mark = 248; // marker for a (theoretical ;-)) 5-byte-char and mask for a 4-byte-char;

 
$html = EMPTY_STRING;
  for(
$str_pos = 0; $str_pos < strlen($utf); $str_pos++) {
  
$old_chr = $utf{$str_pos};
  
$old_val = ord( $utf{$str_pos} );
  
$new_val = 0;

  
$utf8_marker = 0;

  
// skip non-utf-8-chars
  
if( $old_val > 127 ) {
    
$mark = $max_mark;
     for(
$byte_ctr = $max_count; $byte_ctr > 2; $byte_ctr--) {
      
// actual byte is utf-8-marker?
      
if( ( $old_val & $mark  ) == ( ($mark << 1) & 255 ) ) {
        
$utf8_marker = $byte_ctr - 1;
         break;
       }
      
$mark = ($mark << 1) & 255;
     }
   }

  
// marker found: collect following bytes
  
if($utf8_marker > 1 and isset( $utf{$str_pos + 1} ) ) {
    
$str_off = 0;
    
$new_val = $old_val & (127 >> $utf8_marker);
     for(
$byte_ctr = $utf8_marker; $byte_ctr > 1; $byte_ctr--) {

      
// check if following chars are UTF8 additional data blocks
       // UTF8 and ord() > 127
      
if( (ord($utf{$str_pos + 1}) & 192) == 128 ) {
        
$new_val = $new_val << 6;
        
$str_off++;
        
// no need for Addition, bitwise OR is sufficient
         // 63: more UTF8-bytes; 0011 1111
        
$new_val = $new_val | ( ord( $utf{$str_pos + $str_off} ) & 63 );
       }
      
// no UTF8, but ord() > 127
       // nevertheless convert first char to NCE
      
else {
        
$new_val = $old_val;
       }
     }
    
// build NCE-Code
    
$html .= '&#'.$new_val.';';
    
// Skip additional UTF-8-Bytes
    
$str_pos = $str_pos + $str_off;
   }
   else {
    
$html .= chr($old_val);
    
$new_val = $old_val;
   }
  }
  return(
$html);
}
?>


alexey at NOSPAMPLS dot ozerov dot de
31-Aug-2005 09:30

Notice that the path to the TrueType font has to be included in open_basedir list if open_basedir restriction is activated in php.ini.


gav-alex at bk dot ru
10-Aug-2005 06:05

Hi all!
When my hoster updated his php's libs at first minutes i've got the same problem as some of you.
Php couldn't find the path to true type fonts.
The solution in my case was to make the path look like this
<?php
imagettftext
($im, 20, 0, 620, 260, $secondary_color, "./tahoma.ttf" , "NEWS");
?>
so as you can see i simply added "./"

another tip that i wanted to add here is how to write in RUssian on image using imagettftext
you simply have to change the function argument like this
<?php
imagettftext
($im, 15, 0, 575, 300, $secondary_color, "./tahoma.ttf" , win2uni("some word in russian"));
 
?>
where win2uni is the function that converts win1251 to unicode. here is the code of it
<?php

 
//  Windows 1251 -> Unicode
 
function win2uni($s)
  {
  
$s = convert_cyr_string($s,'w','i'); //  win1251 -> iso8859-5
   //  iso8859-5 -> unicode:
  
for ($result='', $i=0; $i<strlen($s); $i++) {
    
$charcode = ord($s[$i]);
    
$result .= ($charcode>175)?"&#".(1040+($charcode-176)).";":$s[$i];
   }
   return
$result;
  }
?>

That's all today! Thanks for your attention!
Alex


BuddyHacker
21-Jul-2005 11:55

A correction to Paul Reinheimer's note above regarding this PHP error:

Fatal error: Call to undefined function imagettftext().

Paul states that you need XPM libraries to resolve this issue.  This is not true.  There is an error message that originates from "configure" which mistakenly shows itself when other components are missing.  For instance, if you tell "configure" to add JPEG support, and it can't find the libraries, it will tell you it can't find the JPEG libraries AND it will recommend adding --with-xpm to solve the problem.  This recommendation is ill-placed and misleading.

I received the same error message above, along with the recommendation to add XPM supprt.  However I resolved it by adding the --with-freetype-dir  AND --enable-gd-native-ttf  options  to the "configure" command line.  I did _not_ need XPM.

There are other variations to this error message, such as the script recommending adding JPEG support or PNG support to resolve it's own inability to locate other libraries.  The script needs some cleanup in order to fix these poorly placed recommendations.

FYI, imagettftext() is a call to one of the truetype fonts functions.  It is NOT related in any way to the XPM libraries, so it is not required unless you explicitly want XPM functionality.


nick
01-Apr-2005 11:18

A trivial function to get right or centre aligned horizontal text:

function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L') {
  
   //check width of the text
   $bbox = imagettfbbox ($size, $angle, $font, $text);
   $textWidth = $bbox[2] - $bbox[0];
   switch ($alignment) {
       case "R":
           $x -= $textWidth;
           break;
       case "C":
           $x -= $textWidth / 2;
           break;
   }
      
   //write text
   imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);

}


erik[at]phpcastle.com
04-Mar-2005 01:46

Remember!!!

When uploading a font to your website you have to set the transfer mode to binary. It took me some time to find out :P. Tried to download the font from my website and it was spoiled.

In your script, the path to your font, use realpath("arial.ttf") so there is no confusion about that.


pillepop2003 at nospam dot yahoo dot de
12-Jan-2005 02:14

Hey guys,

check this function if you want to rotate the text around its center and not its "lower left" pivot-point:

<?php
      
// Put center-rotated ttf-text into image
       // Same signature as imagettftext();
      
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
       {
          
// retrieve boundingbox
          
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
          
          
// calculate deviation
          
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;        // deviation left-right
          
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;        // deviation top-bottom
          
           // new pivotpoint
          
$px = $x-$dx;
          
$py = $y-$dy;
          
           return
imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
       }

?>

Big up
Phil


Paul Reinheimer
20-Sep-2004 12:33

If you compiled PHP yourself but get an error:
Fatal error: Call to undefined function imagettftext().

You need to compile PHP with more options.

--with-gd
--enable-gd-native-ttf
--with-png
--with-zlib-dir=/usr/local/lib/zlib-1.2.1
--with-ttf
--with-jpeg-dir=/usr/local/lib/jpeg-6b/
--with-freetype-dir=/usr/local/lib/freetype-2.1.9/
--with-xpm-dir=/usr/X11R6/

The next set deal with setting up GD, and the appropriate options. Just enabling GD, ttf, png & jpeg is NOT enough. You also need Freetype and XPM.


plusplus7 at hotmail dot com
15-Jul-2004 10:37

If you are getting all rectangles instead of text, it may well mean that your ttf font is not opentype, particularly if it is an older freeware one. This requirement didn't exist in older versions so you may find that your font stops working after you upgrade. To fix this problem, try downloading the free MS Volt utility. From there, open your font file, and then click on Compile, and resave.


02-Dec-2002 08:13

If you have an older version of the GD library, but wish to use a font file which has spaces in the path, you should convert the path into DOS style names. This will only work on windows.

For example:
C:\reallylongpath\reallylongpath\font.ttf
Would become:
C:\really~1\really~1\font.ttf


imacs at email dot com
06-Apr-2000 11:16

To make it support chinese and japanese fonts, have a look here.
* http://www.freshmeat.net/appindex/1999/12/27/946305846.html


 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt