|
Resource Center
: PHP
: <PHP Imaging support & Image manipulation - An overview of possibilities>
|
|
PHP Imaging support & Image manipulation - An overview of possibilities
Posted by: Floresense Team
<?php
//prints header to browser..
header("Content-type: image/png");
//string message
$string = "Welcome";
//load another image, a button image
$im = imagecreatefrompng("images/button1.png");
//create color pen
$black = imagecolorallocate($im, 0, 0, 0);
//get center point on image
$px = (imagesx($im) - 7.5 * strlen($string)) / 2;
//print message on image
imagestring($im, 5, $px, 9, $string, $white);
//output new image
imagepng($im);
//free space used by object
imagedestroy($im);
?>
The above code generates a button image with our text "Welcome" literally written on the button as if it was drawn on the button using an imaging tool.
The line imagecreatefrompng("images/button1.png"); loads a png image stored on the local system in the relative path of the PHP script under images folder.
We haven't set the size of the image through an imagecreate() function and so the image $im assumes the size of the button image.
You can also use functions like imagecreatefromgif or imagecreatefromjpeg to load gif or jpg format images. More functions for other formats might be available if your GD library and PHP version are more current. Such as, imagecreatefromwbmp, imagecreatefromxbm, and imagecreatefromxpm.
Example: $im = imagecreatefromjpeg("photo.jpg");
Above code outputs:
You can use URLs inside these functions, its not limited to relative path.
imagecreatefromgif(http://www.someWebSite.com/images/txt_something.gif);
If the URL of the image path has a space or special characters, it has to be properly URL encoded.
Sample HTTP encoded URL: http://www.someWebSite.com/images/txt%20something.gif
Getting Image size: When generating images / loading images whose size we don't know until we see the image, we might be interested to the image size parameters to add it to our HTML or for calculating the center position on the image to place text. As seen in the sample code earlier, we could use imagesx() or imagesy() methods to get the width and height of the image.
$im = imagecreatefrompng("images/button1.png");
$width = imagesx($im);
$height =imagesy($im);
Another way to do this is, by using getimagesize() method which in one line gets all the parameters about the image. <?
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
?>
Above code loads a list of variables with width, height, type and attr data in the array columns.
The output of getimagesize() function is an array, and hence this syntax is the easiest and makes it a simple one line code. Though, to load an array, we would use: <?
$imgParams = getimagesize("img/flag.jpg");
$width = $imgParams[0];
?>
Advertisement
|