PHPのお勉強!

PHP TOP

imagestring

(PHP 4, PHP 5, PHP 7, PHP 8)

imagestring文字列を水平に描画する

説明

imagestring(
    GdImage $image,
    GdFont|int $font,
    int $x,
    int $y,
    string $string,
    int $color
): bool

指定した座標に文字列 string を描画します。

パラメータ

image

imagecreatetruecolor()のような画像作成関数が返す GdImage オブジェクト。

font

latin2 エンコーディングの組み込みのフォントの場合は 1, 2, 3, 4, 5 のいずれか (数字が大きなほうが、より大きいフォントに対応します)、あるいは imageloadfont() が返した、GdFont クラスのインスタンスのいずれか。

x

左上隅の x 座標。

y

左上隅の y 座標。

string

書き出す文字列。

color

imagecolorallocate() で作成された色識別子。

戻り値

成功した場合に true を、失敗した場合に false を返します。

変更履歴

バージョン 説明
8.1.0 引数 font は、GdFont クラスのインスタンスと数値を両方受け入れるようになりました。これより前のバージョンでは、数値のみを受け入れていました。
8.0.0 image は、 GdImage クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、有効な gd resource が期待されていました。

例1 imagestring() の例

<?php
// 100*30 の画像を生成します
$im = imagecreate(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/png");

imagepng($im);
imagedestroy($im);
?>

上の例の出力は、 たとえば以下のようになります。

出力例 : imagestring()

参考

add a note

User Contributed Notes 30 notes

up
28
keksnicoh at googlemail dot com
16 years ago
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, $text, 1, 6));
?>

Have fun :)
up
6
Booteille
9 years ago
Here is a function with similar declaration of imagestring() but who handles whitespaces (It creates new lines and 4 spaces instead of \n and \t) and image's size limits

<?php

/**
* @author Booteille
*
* @param resource $image
* @param int $font
* @param int $x
* @param int $y
* @param string $string
* @param int $color
*/
function whitespaces_imagestring($image, $font, $x, $y, $string, $color) {
$font_height = imagefontheight($font);
$font_width = imagefontwidth($font);
$image_height = imagesy($image);
$image_width = imagesx($image);
$max_characters = (int) ($image_width - $x) / $font_width ;
$next_offset_y = $y;

for(
$i = 0, $exploded_string = explode("\n", $string), $i_count = count($exploded_string); $i < $i_count; $i++) {
$exploded_wrapped_string = explode("\n", wordwrap(str_replace("\t", " ", $exploded_string[$i]), $max_characters, "\n"));
$j_count = count($exploded_wrapped_string);
for(
$j = 0; $j < $j_count; $j++) {
imagestring($image, $font, $x, $next_offset_y, $exploded_wrapped_string[$j], $color);
$next_offset_y += $font_height;

if(
$next_offset_y >= $image_height - $y) {
return;
}
}
}
}

?>
up
1
jordanslost at gmail
15 years ago
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, -1 ); // 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( $image, 2, $x, $y, $letter, $light_blue );
$first = false;

} else {

$x = ( $x - $minus );
imagestring( $image, 2, $x, $y, $letter, $light_blue );

}

}
?>
up
0
eviloverlord+php at gmail dot com
16 years ago
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($img, true);
$trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $trans_colour);

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

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

//Output the image
imagepng($img);
imagedestroy($img);
?>
up
0
gannon (at) portablesofdoom (dot) org
17 years ago
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));
}
up
0
Piotr dot Sulecki at traxelektronik dot pl
18 years ago
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.
up
-2
deejay_world at yahoo dot com
22 years ago
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) );
up
-1
aly at slo-igre dot net
19 years ago
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.
up
-2
sk89q
16 years ago
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($text, floor($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;
}
?>
up
-1
wheberson dot com dot br at gmail dot com
5 years ago
// Convert e-mail to image (png)
function convertEmailToImg ($aValue, $aRed, $aGreen, $aBlue, $aAlphaF=0, $aAlphaB=127, $aFontSize=4)

{
$img= imagecreatetruecolor (imagefontwidth ($aFontSize) * strlen ($aValue), imagefontheight ($aFontSize));
imagesavealpha ($img, true);
imagefill ($img, 0, 0, imagecolorallocatealpha ($img, 0, 0, 0, $aAlphaB));
imagestring ($img, $aFontSize, 0, 0, $aValue, imagecolorallocatealpha ($img, $aRed, $aGreen, $aBlue, $aAlphaF));
ob_start ();
imagepng ($img);
imagedestroy ($img);
return base64_encode (ob_get_clean ());
}

// Example
$imgString= convertEmailToImg ('contact@example.com', 0, 0, 255, 0, 127, 4);
up
-2
jlamer
17 years ago
// 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);
}
up
-1
cesargus at yahoo dot com
20 years ago
//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);
?>
up
-2
mustafa at hafunny dot info
16 years ago
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(200, 20);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
$text = "ľščťžýáíéúäňôď...";

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

// write converted string at the top left
imagestring($im, 4, 0, 0, $string, $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?>
up
-2
iibm at free dot fr
18 years ago
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);
}
?>
up
-2
webmaster at acdrifter dot com
19 years ago
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 );
}
up
-2
php dot net at mvoncken dot nl
21 years ago
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)
up
-3
mike at mike-griffiths dot co dot uk
16 years ago
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($img, 25, 25, 25);
// White font color
$color = imagecolorallocate($img, 255, 255, 255);
// 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($string, 1);

}
// Return the image
header("Content-Type: image/gif");
imagegif($img);
// Remove image
imagedestroy($img);

?>