Sometimes could be useful to write a text into image, I'm thinking to those images usally published on facebook.
Generating such images using php is very simple, only five calls have to be used:
imagecreatetruecolor to create the image
imagefilledrectangle to create the background
imagettftext to draw the string
imagepng to save the file
imagedestroy to release memory
Note: I'm using Mac OS X so I have to load fonts from the /Library/Fonts/ directory
Save as drawstring.php the following script:
#!/usr/bin/php
<?php
// Create the image
$im = imagecreatetruecolor(400, 60);
// Create some colors
$red = imagecolorallocate($im, 255, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255 );
imagefilledrectangle($im, 0, 0, 400, 60, $red);
// The text to draw
$text = $argv[1];
// Replace path by your own font path
$font = '/Library/Fonts/Arial Black.ttf';
// Add the text
imagettftext($im, 20, 0, 10, 20, $white, $font, $text);
imagepng($im, 'simpleimage.png');
imagedestroy($im);
?>
# chmod +x drawstring.php
# ./drawstring.php "Gigi il bello"
and here you are the result:
Maybe you want to draw your text in two different lines, you have to change the script in such a way:
#!/usr/bin/php
<?php
// Create the image
$im = imagecreatetruecolor(400, 60);
// Create some colors
$red = imagecolorallocate($im, 255, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 400, 60, $red);
// The text to draw
$text1 = $argv[1];
$text2 = $argv[2];
$text = $argv[1]."\n".$argv[2];
// Replace path by your own font path
$font = '/Library/Fonts/Arial Black.ttf';
// Add the text
imagettftext($im, 20, 0, 10, 20, $white, $font, $text);
imagepng($im, 'simpleimage.png');
imagedestroy($im);
?>
# ./drawstring.php "Gigi" "il bello"
Gg1