Page 278 - Open Soource Technologies 304.indd
P. 278
Web Technologies-I
Notes GD Image Processing Library to provide all the powerful tools you need to accomplish this task.
The most basic tasks in image processing: scaling.
The first thing we should do is make sure the GD image library is actually installed. To access
this data, we can call the gd_info() function. To display it, we can call the “var_dump()” function
with gd_info() as a parameter. Run this code:
var_dump(gd_info());
If you get a messy-looking string with the GD version and other info, you should be good.
Otherwise, you need to figure out how to install/activate the library. Now that’s taken care of,
we can start the real code.
Our particular resize program will scale based on a single factor instead of scaling to a target
size. More work can be done to make this a much smarter program, but for time and complexity
constraints we will just be using this simple method.
First thing we should do is lay out the variables that we will need to control the operation of
this script. The “$source” as a string containing the path to the image we will be using as the
source, “$dest” as the path of the image that will be the result of the resize/scale operation,
“$quality” will be a number between 0 and 100 representing the quality of the output JPG file (0
is worst quality, 100 is highest quality), and “$scale” will be a floating point number containing
the ratio of the new image to the source image. Fortunately, PHP syntax allows us to write
this floating point much like a fraction and thus a scale operation of one half can be written as
“1/2″ instead of “.5″.
$source = “source_image.jpg”;
$dest = “resized_image.jpg”;
$quality = 100;
$scale = 1/2;
Next, we should gather some information about the source image and then perform calculations
resulting on the size of the desired destination image. “getimagesize()” will return an array
containing the width and height respectively. The product of each dimension and the “$scale”
factor will give us the desired new dimensions, which we will call “$x” and “$y”.
$imsize = getimagesize($source);
$x = $scale * $imsize[0];
$y = $scale * $imsize[1];
Now we need to load the image into the server memory. Assuming the source image is a jpg,
we can do this using the “imagecreatefromjpeg()” function. If you are using a different type of
image, use this table to decide which function to use, and replace the code example with the
function you need.
Source Image Type Function to Use
JPG imagecreatefromjpeg()
GIF imagecreatefromgif()
PNG imagecreatefrompng()
BMP imagecreatefromwbmp()
So initialize the image object container with a variable assignment using the correct function
from the above table:
272 LOVELY PROFESSIONAL UNIVERSITY