Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
imagechar() function in PHP
The imagechar() function in PHP draws a single character horizontally on an image. This function is useful for adding text elements to dynamically generated images.
Syntax
bool imagechar(resource $image, int $font, int $x, int $y, string $c, int $color)
Parameters
image − An image resource created by functions like
imagecreate()orimagecreatetruecolor()font − Font size (1-5 for built-in fonts, or a loaded font identifier)
x − x-coordinate for the character position
y − y-coordinate for the character position
c − The character to draw (only the first character of the string is used)
color − A color identifier created with
imagecolorallocate()
Return Value
Returns TRUE on success or FALSE on failure.
Example 1: Drawing a Single Character
Here's how to draw a single character on an image ?
<?php
// Create a 400x300 image
$img = imagecreate(400, 300);
// Allocate colors
$bgcolor = imagecolorallocate($img, 30, 80, 70);
$textcolor = imagecolorallocate($img, 255, 255, 255);
// Draw character 'A' at position (100, 90) with font size 5
imagechar($img, 5, 100, 90, 'A', $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
Example 2: Multiple Characters with Different Positions
Drawing multiple characters by calling the function multiple times ?
<?php
// Create a 350x270 image
$img = imagecreate(350, 270);
// Allocate colors
$bgcolor = imagecolorallocate($img, 70, 100, 130);
$textcolor = imagecolorallocate($img, 200, 195, 210);
// Draw characters 'P', 'H', 'P' at different positions
imagechar($img, 4, 50, 70, 'P', $textcolor);
imagechar($img, 4, 70, 70, 'H', $textcolor);
imagechar($img, 4, 90, 70, 'P', $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
Key Points
Only the first character of the string parameter is drawn
Font sizes 1-5 are built-in fonts (1 is smallest, 5 is largest)
For drawing complete strings, use
imagestring()insteadAlways call
imagedestroy()to free memory after image operations
Conclusion
The imagechar() function is ideal for drawing individual characters on images. For complete text rendering, consider using imagestring() or imagettftext() for more advanced typography options.
