Programming

PHP-GD: Create Image from Text

Some people want to hide their text into image for any reason. As example, to avoid spambot steal their email address, or to generate dynamic images content.

Its simply done with PHP and GD Library. See this simple function:

function imgfromstring($string){
	$font  = 5;
	//dynamic size of image. to fit your text.
	$width  = ImageFontWidth($font) * strlen($string);
	$height = ImageFontHeight($font);

	//start creating the image
	$gbr = imagecreate ($width,$height);

	//set background to white
	$bgcolor = imagecolorallocate($gbr, 255, 255, 255);
	//set color for text
	$txtcolor = imagecolorallocate ($gbr, 0, 0, 0);

	//generate the image
	imagestring($gbr, $font, 0, 0, $string, $txtcolor);
	header("Content-type: image/jpeg");
	return imagejpeg($gbr);
}

//usage:
$txt = "user@email.com";
echo imgfromstring($txt);

example output:

Another sample is using image as the background. Its useful when you need to create waterwark to protect your images.
Sample code:

function toImgWithBG($str){
	$bg = "background.jpg";
	$font = 5; //Font size

	$gbr =imagecreatefromjpeg($bg);

	//Calculate string width and height
	$pos_x  = imagesx($gbr) - (ImageFontWidth($font) * strlen($str));
	$pos_y = imagesy($gbr) - ImageFontHeight($font);

	//set text color
	$teks = imagecolorallocate($gbr, 255, 0, 0);

	//generate the image, and put on the right bottom
	imagestring($gbr, 5, $pos_x, $pos_y, $str, $teks);

	header("Content-type: image/jpeg");
	return imagejpeg($gbr);
}

//Usage:
echo toImgWithBG("copyright: http://www.akemapa.com/");

example output:

You can download source code of this example here:
download here download this file

Programming

PHP-GD: Resize Transparent Image PNG & GIF

By default, you will get black background if you resize a transparent image. Play Daisy slots to see how good the quality of the background images are. To fix it, you need set alpha channel imagecolorallocatealpha to 127.
With imagecolorallocatealpha, it will allocate a color for an image.

Usage:
int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha)

From PHP manual:
imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.

Before using it, you must set to false the blending mode for an image and set true the flag to save full alpha channel information.

Example:

<? $newImg = imagecreatetruecolor($nWidth, $nHeight); imagealphablending($newImg, false); imagesavealpha($newImg,true); $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent); imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]); ?>