How to Use PHP To Dynamically Resize an Image
We’re going to make use of the PHP GD library to manipulate the image, and a $_GET parameter to tell it which image to re-size.
Let’s walk through using the GD library to re-size an image. Then we’ll see how to include that in your HTML to actually do the resizing for you.
First, we need to open up the original file and get it’s size and type characteristics.
$src_img = imagecreatefrompng(’image.png’);
$srcsize = getimagesize(’image.png’);
imagecreatfrompng() creates an image object and stores it in $src_image. If the file was a different type we could replace “png” with “jpeg” or “gif.” getimagesize() stores an array in $srcsize that contains the width of the image ($srcsize[0]), the height of the image ($srcsize[1]), and the filetype of the image ($srcsize[2]).
Now we need to create new dimensions for the new image and actually create an image. We’ll resize it to 200 pixels wide - and then adjust the height to maintain the ratio.
$dest_x = 200;
$dest_y = (200 / $srcsize[0]) * $srcsize[1];
$dst_img = imagecreatetruecolor($dest_x, $dest_y);
imagecreatetruecolor() creates a new image object for us with the given dimensions - which we will soon fill in with our resized image.
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0,
$dest_x, $dest_y, $srcsize[0], $srcsize[1]);
header(”content-type: image/png”);
imagepng($dst_img);
imagecopyresampled() copies an image ($dst_img) into a new image ($src_img) with a set of given attributes (including our sizes). The “Header” line tells the browser that this is an image - so that it’s not displayed as a bunch of gibberish. Finally, the imagepng() function actually displays the image.
Now, we need to clean up and destroy the image objects. Otherwise, we could end up sapping a lot of memory from the server.
imagedestroy($src_img);
imagedestroy($dst_img);
Displaying the Script in HTML
If you load the script directly, you should simply see the image. It creates an image resource and displays it in the browser - as if “resize-image.php” was really “image.png.”
Therefore all we need to do to include this new image in an HTML page is use the php script as the src attribute of our <img> tag. Like so…
<img src=’resize-image.php’ />
Posted by Mahesh ( Tryangled )