Vous êtes sur la page 1sur 17

About PHP GD: In this tutorial you will get to know about PHP GD, The GD library is used

to create dynamic image creation. GD is an open source code library, This tutorial also includes the steps by which you can enable the GD option of WAMP server. What is PHP GD Library GD: The GD graphics library is a developed by Thomas Boutell. Previously Gd stood for "GIF Draw" after some legal issues now it stood for "Graphics Draw". GD supports numerous languages like C, PHP, Tcl, Lua, REXX, Ruby etc. The GD library is used to create dynamic image creation. GD is an open source code library and written in 'C' and wrappers are available for Perl, PHP and other languages. GD can create images composed of lines, arcs, other images etc. It can used to create and manipulate image files in a variety of different image formats including GIF, PNG, JPEG, WBMP, and XPM etc. We can generate charts, graphics, thumbnails, etc. It can do some complex tasks like complex graphic editing: grayscaling or applying other filters to a photo, anti-robot security image. Most common applications of GD involve web-site development.

Features of PHP GD Library: 1. GD is an open source code library 2. Written in 'C' 3. Wrappers are available for Perl, PHP and other languages 4. Create images composed of lines, arcs etc. 5. Generate charts, graphics, thumbnails, etc 6. It supports different image formats including GIF, PNG, JPEG, WBMP, and XPM etc 7. It can do some complex tasks like complex graphic editing: grayscaling etc.

How to enable GD option in WAMP: i) Run WAMP server:

ii) Select PHP settings from PHP option:

iii) Check php_gd2 option, if it is unchecked (by default it is checked)

Introduction PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with. You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images. With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library. Note: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension. Note: The getimagesize() function does not require the GD extension.

Requirements If you have the GD library (available at http://www.libgd.org/) you will also be able to create and manipulate images. The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28. Note: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since its codebase is better maintained and more stable. You may wish to enhance GD to handle more image formats. Supported image formats Image format gif Library to download Notes Only supported in GD versions older than gd1.6 and newer than gd-

Supported image formats Image format Library to download Notes 2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1. When building the jpeg library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP. Only supported in GD versions greater than gd-1.6. It's likely you have this library already available, if your system has an installed X-Environment.

jpeg

http://pecl2.php.net/downloads/php-windowsbuilds/source/

png

http://www.libpng.org/pub/png/libpng.html

xpm

ftp://metalab.unc.edu/pub/Linux/libs/X/! INDEX.html

You may wish to enhance GD to deal with different fonts. The following font libraries are supported: Supported font libraries Font library Download Notes This deprecated feature will certainly be removed in the future.

FreeType http://www.freetype.org/ 1.x FreeType http://www.freetype.org/ 2 T1lib ftp://sunsite.unc.edu/pub/Linux/libs/graphics/)

Support for Postscript Type 1 fonts.

Installation

To enable GD-support configure PHP --with-gd[=DIR] , where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option --with-gd . GD library requires libpng and libjpeg to compile. In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2. Enhance the capabilities of GD to handle more image formats by specifying the --withXXXX configure switch to your PHP configure line. Supported image formats Image Format jpeg png xpm Configure Switch To enable support for jpeg add --with-jpeg-dir=DIR . Jpeg 6b, 7 or 8 are supported. To enable support for png add --with-png-dir=DIR . Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line. To enable support for xpm add --with-xpm-dir=DIR . If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Note: When compiling PHP with libpng, you must use the same version that was linked with the GD library. Enhance the capabilities of GD to deal with different fonts by specifying the --withXXXX configure switch to your PHP configure line. Supported font libraries Configure Switch To enable support for FreeType 1.x add --with-ttf[=DIR] . To enable support for FreeType 2 add --with-freetypedir=DIR . To enable support for T1lib (Postscript Type 1 fonts) add with-t1lib[=DIR] . To enable support for native TrueType string function add --enable-gd-native-ttf .

Font library FreeType 1.x FreeType 2 T1lib Native TrueType string function

PHP Form Image Upload

This tutorial shows you how to upload an image on your server using PHP and html forms. You will also learn how to verify if the uploaded file is an image (checking the extension), if it doesn't overtakes a size limit and how to change the uploaded file name. Important: You must set the enctype form atribute to "multipart/formdata", otherwise the form will not show you any errors, but it will just not upload your images! Step 1: Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won't work ( it won't be able to upload the files into the directory). Step 2: Paste the following code into a php file. Please read carefuly the comments. All steps are explained there. <?php //define a maxim size define("MAX_SIZE","100");

for

the

uploaded

images

in

Kb

//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i=strrpos($str,"."); if(!$i) { return""; $l=strlen($str)-$i; $ext=substr($str,$i+1,$l); return$ext; } //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an }

errro occures. If the error occures the file will not beuploaded.

$errors=0; //checks

if

the

form

has

been

submitted

if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['image']['name']; //if it is not empty if($image) { //get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['name']); //get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); //if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { //print error message echo '<h1>Unknown extension!</h1>'; $errors=1; } else { //get the size of the image in bytes //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server $size=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($size > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format

$image_name=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; //we verify if the image has been uploaded, and print error instead $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "<h1>File Uploaded Successfully! Try again!</h1>"; } ?> <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" --> <form name="newad" method="post" enctype="multipart/form-data" action=""> <table> <tr><td><input type="file" name="image"></td></tr> <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr> </table> </form>

GD and Image Functions


Table of Contents

gd_info Retrieve information about the currently installed GD library getimagesize Get the size of an image

image_type_to_extension Get file extension for image type image_type_to_mime_type Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype image2wbmp Output image to browser or file imagealphablending Set the blending mode for an image imageantialias Should antialias functions be used or not imagearc Draws an arc imagechar Draw a character horizontally imagecharup Draw a character vertically imagecolorallocate Allocate a color for an image imagecolorallocatealpha Allocate a color for an image imagecolorat Get the index of the color of a pixel imagecolorclosest Get the index of the closest color to the specified color imagecolorclosestalpha Get the index of the closest color to the specified color + alpha imagecolorclosesthwb Get the index of the color which has the hue, white and blackness imagecolordeallocate De-allocate a color for an image imagecolorexact Get the index of the specified color imagecolorexactalpha Get the index of the specified color + alpha imagecolormatch Makes the colors of the palette version of an image more closely match the true color version imagecolorresolve Get the index of the specified color or its closest possible alternative imagecolorresolvealpha Get the index of the specified color + alpha or its closest possible alternative imagecolorset Set the color for the specified palette index imagecolorsforindex Get the colors for an index imagecolorstotal Find out the number of colors in an image's palette imagecolortransparent Define a color as transparent imageconvolution Apply a 3x3 convolution matrix, using coefficient and offset imagecopy Copy part of an image imagecopymerge Copy and merge part of an image imagecopymergegray Copy and merge part of an image with gray scale imagecopyresampled Copy and resize part of an image with resampling imagecopyresized Copy and resize part of an image imagecreate Create a new palette based image imagecreatefromgd2 Create a new image from GD2 file or URL imagecreatefromgd2part Create a new image from a given part of GD2 file or URL imagecreatefromgd Create a new image from GD file or URL imagecreatefromgif Create a new image from file or URL imagecreatefromjpeg Create a new image from file or URL imagecreatefrompng Create a new image from file or URL imagecreatefromstring Create a new image from the image stream in the string imagecreatefromwbmp Create a new image from file or URL imagecreatefromxbm Create a new image from file or URL imagecreatefromxpm Create a new image from file or URL imagecreatetruecolor Create a new true color image

imagedashedline Draw a dashed line imagedestroy Destroy an image imageellipse Draw an ellipse imagefill Flood fill imagefilledarc Draw a partial arc and fill it imagefilledellipse Draw a filled ellipse imagefilledpolygon Draw a filled polygon imagefilledrectangle Draw a filled rectangle imagefilltoborder Flood fill to specific color imagefilter Applies a filter to an image imagefontheight Get font height imagefontwidth Get font width imageftbbox Give the bounding box of a text using fonts via freetype2 imagefttext Write text to the image using fonts using FreeType 2 imagegammacorrect Apply a gamma correction to a GD image imagegd2 Output GD2 image to browser or file imagegd Output GD image to browser or file imagegif Output image to browser or file imagegrabscreen Captures the whole screen imagegrabwindow Captures a window imageinterlace Enable or disable interlace imageistruecolor Finds whether an image is a truecolor image imagejpeg Output image to browser or file imagelayereffect Set the alpha blending flag to use the bundled libgd layering effects imageline Draw a line imageloadfont Load a new font imagepalettecopy Copy the palette from one image to another imagepng Output a PNG image to either the browser or a file imagepolygon Draws a polygon imagepsbbox Give the bounding box of a text rectangle using PostScript Type1 fonts imagepsencodefont Change the character encoding vector of a font imagepsextendfont Extend or condense a font imagepsfreefont Free memory used by a PostScript Type 1 font imagepsloadfont Load a PostScript Type 1 font from file imagepsslantfont Slant a font imagepstext Draws a text over an image using PostScript Type1 fonts imagerectangle Draw a rectangle imagerotate Rotate an image with a given angle imagesavealpha Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images imagesetbrush Set the brush image for line drawing imagesetpixel Set a single pixel imagesetstyle Set the style for line drawing imagesetthickness Set the thickness for line drawing imagesettile Set the tile image for filling imagestring Draw a string horizontally imagestringup Draw a string vertically imagesx Get image width imagesy Get image height imagetruecolortopalette Convert a true color image to a palette image imagettfbbox Give the bounding box of a text using TrueType fonts imagettftext Write text to the image using TrueType fonts

imagetypes Return the image types supported by this PHP build imagewbmp Output image to browser or file imagexbm Output XBM image to browser or file iptcembed Embeds binary IPTC data into a JPEG image iptcparse Parse a binary IPTC block into single tags. jpeg2wbmp Convert JPEG image file to WBMP image file png2wbmp Convert PNG image file to WBMP image file

This tutorial is about the displaying the hello world in PHP GD Library. <?php ini_set("display_errors", "1"); error_reporting(E_ALL); header('content-type: image/png'); $image = imagecreatetruecolor(300, 300); $dark_grey = imagecolorallocate($image, 102, 102, 102); $white = imagecolorallocate($image, 255, 255, 255); $font_path = 'C:/WINNT/Fonts/arial.ttf'; $string = 'Hello World!'; imagettftext ($image, 30, 0, 10, 130, $white, $font_path, $string); imagegif($image); imagedestroy($image); ?> After running the program you will get the following output

Related Tags for Php gd hello world:

This example shows how to show captcha in php gd. <?php session_start(); class CaptchaSecurityImages { var $font = 'C:/WINNT/Fonts/arial.ttf'; function generateCode($characters) { $possible = '23456789bcdfghjkmnpqrstvwxyz'; $code = ''; $i = 0; while ($i < $characters) { $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);

$i++; } return $code; } function CaptchaSecurityImages($width='120',$height='40',$characters='6') { $code = $this->generateCode($characters); $font_size = $height * 0.75; $image = imagecreate($width, $height) or die('Cannot initialize new GD image stream'); $background_color = imagecolorallocate($image, 255, 255, 255); $text_color = imagecolorallocate($image, 20, 40, 100); $noise_color = imagecolorallocate($image, 100, 120, 180); for( $i=0; $i<($width*$height)/3; $i++ ) { imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); } for( $i=0; $i<($width*$height)/150; $i++ ) { imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height),$noise_color); } $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function'); $x = ($width - $textbox[4])/2; $y = ($height - $textbox[5])/2;

imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function'); header('Content-Type: image/jpeg'); imagejpeg($image); imagedestroy($image); $_SESSION['security_code'] = $code; } } $width = isset($_GET['width']) && $_GET['width'] < 600 ? $_GET['width'] : '120'; $height = isset($_GET['height']) && $_GET['height'] < 200 ? $_GET['height'] : '40'; $characters = isset($_GET['characters']) && $_GET['characters'] > 2 ? $_GET['characters'] : '6'; $captcha = new CaptchaSecurityImages($width,$height,$characters); ?> After running the program you will get the following output

Related Tags for PHP GD captcha:

This example shows how to bold text in php gd. <?php header('Content-type: image/png'); $image = imagecreatetruecolor(400, 30); $red = imagecolorallocate($image, 255, 0, 0);

$grey = imagecolorallocate($image, 128, 128, 128); $black = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, 399, 29, $red); $text = 'RoseIndia...'; $font = 'C:/WINNT/Fonts/arial.ttf'; imagettftext($image, 20, 0, 11, 21, $grey, $font, $text); imagettftext($image, 20, 0, 10, 20, $black, $font, $text); imagepng($image); imagedestroy($image); ?> After running the program you will get the following output

Related Tags for PHP GD bold text:

This example shows how to draw rectangle in php gd. <?php header("Content-type: image/jpeg"); $width = 350; $height = 360; $im = ImageCreateTrueColor($width, $height); ImageAntiAlias($im, true);

$white = ImageColorAllocate($im, 255, 255, 255); ImageFillToBorder($im, 0, 0, $white, $white); $black = ImageColorAllocate($im, 0, 0, 0); $blue = ImageColorAllocate($im, 0, 0, 255); $r_width = 140; $r_height = 90; $r_x = 90; $r_y = 40; ImageRectangle($im, $r_x, $r_y, $r_x+$r_width, $r_y+$r_height, $black); $r_width = 140; $r_height = 90; $r_x = 90; $r_y = 180; ImageFilledRectangle($im, $r_x, $r_y, $r_x+$r_width, $r_y+$r_height, $blue); ImageJPEG($im); ImageDestroy($im); ?> After running the program you will get the following output

Related Tags for PHP GD Draw Rectangle: