PHP Tutorials R R




Instead of using php to create a new image from scratch, what if you want to work with images you already created using other graphics programs? Yes it is possible to edit your images using php. You can add text, correct colors, and even resize.

Image Resizing

You can either take an image and shrink it down to desired size, or you can crop the image. You can make thumbnails from your current images.

Why spend time writing code for resizing images, when you can just use your favorite graphics program to do it? Well, it looks like a waste of time at first, until you need to write an application that will deal with images. Say for instance you want to write a classified ads system with photos, people will upload pictures of varying sizes. Your site would look better if all the pictures have a uniform size. You can use php to resize such pictures before saving them.

The main function for image resizing is ImageCopyResized( ). Basically it copies an image you give to it and resizes it at the same time. You will have the old image and the resized image.

Other functions we're going to use are ImageSX( ), which gets the width of the old image, and ImageSY( ), which returns the height.

In general when you're working on an existing image, you use the functions ImageCreateFromJPEG( ), ImageCreateFromPNG( ), ImageCreateFromGIF( ). Which one you use depends on the image you are going to work on, ie. whether jpg, png, or gif.


Original and Resized images are shown below


The code below is fully commented.

<?php

//header tells browser what type of data will follow

header("Content-type: image/gif");

//tells php where gd library is installed

dl("c:/program files/php/extensions/php_gd2.dll");

//width of the resized image

$new_w=164;

//height of the resized image

$new_h=61;

//sets the size of the new image
//We have used ImageCreate( ) before remember?

$dst_img = ImageCreate($new_w,$new_h);

//function for creating a new image from an existing image
//Note: D:/phpweb/hotspot.gif is the location of my image, so change it to yours

$src_img = ImageCreateFromGif("D:/program files/apache group/apache2/htdocs/hotspot.gif");

//ImageSX gets image width, ImageSY gets height
//All the parameters should be self explanatory except maybe the 0,0,0,0
//the first two 0,0 are the x,y coordinates of the destination image
//the third and 4th zeros are the x,y coordinates of the source image.
//if you use values other than zeros, it means the image will be cropped.

ImageCopyResized($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));

ImageGif($dst_img,"new_image.gif");
?>
<img src=new_image.gif />