How to Use PHP To Dynamically Resize an Image
One of the most annoying things about working with images is getting them into the right size. Screenshots start out huge - and you need to resize them to an appropriate size for your website.
Some blogs automatically resize the pictures for you into a thumbnail - like the image to the right. What if you want the image a different size, though? You could allow the browser to resize it for you, or - better yet - write your own php script to resize the image dynamically.
Why You Shouldn’t Let the Browser Resize Images
Look at the original picture - the small thumbnail created by Wordpress. Notice how large it is - 13.9kb. When Wordpress resizes the image, it also reduces the file size. If I were to include the fullsize image and resize it using css height and width attributes, the file size would not be cut down.
Want proof? Look at the second image to the right - that’s simply resized by the browser. It’s a whopping 284.21kb.
If we write our own php script to resize the image dynamically, we can control both the image size and the file size. Check out the third image to the right - which was resized with a php script. You’ll notice that it looks nicer too - the browser isn’t designed to resize images.
Using the PHP GD Library to Resize the Image
So how do we do this? 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);
The calculations should be self explanatory. imagecreatetruecolor() creates a new image object for us with the given dimensions - which we will soon fill in with our resized image.
The next step is to place the resized image into $dst_img and output the image as Image content.
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' />The script will execute, create an image, and use that as the src.
The last thing we need to do is modify our script so that we can pass it some information.
It wouldn’t do much good if we had to write a new php script for every image we wanted to resize. Instead, we can use the $_GET array to send a variable (the image filename) to our image resizing script.
Here’s the entire image resizing script, with the $_GET variable used for the filename.
// Create source image and dimensions $src_img = imagecreatefrompng($_GET['image']); $srcsize = getimagesize($_GET['image']); $dest_x = 200; $dest_y = (200 / $srcsize[0]) * $srcsize[1]; $dst_img = imagecreatetruecolor($dest_x, $dest_y); // Resize image imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_x, $dest_y, $srcsize[0], $srcsize[1]); // Output image header("content-type: image/png"); imagepng($dst_img); // Destroy images imagedestroy($src_img); imagedestroy($dst_img);
To use this, you need to slightly modify your HTML and add an “image” parameter to the URL of your script. Like so…
<img src='resize-image.php?image=image.png' />There ya go! Now you can resize images on the fly.
Next Steps to Take…
This is of course a basic introduction to the topic. You can add a lot of functionality to resize-image.php.
For example, you could take extra parameters - like a width and/or height. You might also want to include a bunch of error checking - make sure the file exists, make sure the new dimensions are appropriate, etc.
You could also use a switch() statement to open different types of images - based on the contents of $srcsize[2]. Remember, you can use the GD library to do more than work with .png files. By replacing ‘png’ with ‘jpeg’ or ‘gif’ you can use the same functions to work with these file types. For example, imagecreatefromjpeg is equivalent to imagecreatefrompng.
In the near future, I plan on extending this example into a full-fledged script for immediate download and use. So stay tuned - and leave any comments with suggestions for what the script should be able to do.







Tutorial Center said this on January 31st, 2008 at 12:55 pm
Would you be able to make on that caches the smaller image? Been looking for a while now..
Walkere said this on January 31st, 2008 at 6:19 pm
It would be possible. I was thinking of writing that up in a later tutorial.
If you add a second parameter (a filename) to the imagepng() function, it will write the image to a file.
You could then create a base script that decides whether or not a cached version has been created. If there is, it just returns the filename to place in the “src” attribute. Otherwise, it calls the image-resizing script to create a cached copy and then returns the filename.
Then you could either clean up every so often with a cron job, or have the script check for old images every time it runs. (Using a small db table to hold the data and the expiration times)
Patrick Blanchard said this on February 23rd, 2008 at 12:15 pm
What about other image formats?
JPG, BMP, GIF ??
(Ok, maybe not bmp…. lol)
Walkere said this on February 23rd, 2008 at 5:16 pm
Like I mentioned towards the end, you can easily change this to work with any major image format. The imagecreatefrompng() is specific to png files - but the GD library also has imagecreatefromjpeg() and imagecreatefromgif().
By using a switch statement at the beginning, based on the results of getimagesize(), you can have it automatically choose which format to load. Similarly, use a switch at the end to choose between imagepng(), imagegif(), and imagejpeg().
There is, unfortunately, no support for regular .bmp files. Time to upgrade =)
Pat said this on February 26th, 2008 at 7:31 pm
I just md5 the image name and size and cache it then if the image or size ever changes it will create a new one and cache it on the server, a simple check can prevent having the server resize the image again.
Nice tute, the only problem I have encountered is client caching, anyone know what headers should be sent with the dynamic image to chache it on the client computer?
How to Enable Client-Side Caching of Resized Images | Web Cash said this on March 1st, 2008 at 7:37 pm
[…] a month ago, I wrote a tutorial on dynamically resizing images in PHP. Despite my best intentions, I never found the time to go back and rewrite the script to include […]
Traffic Through Social Bookmarking | Web Cash said this on March 12th, 2008 at 4:00 pm
[…] articles were moderately successful. One article I didn’t submit myself - a reader Dugg it and it promptly gained about 20 Diggs. Despite its […]
srinivas.m said this on March 27th, 2008 at 4:52 am
hi,
this is srinivas. this code is very much useful in my website thank you.
poncho said this on April 18th, 2008 at 12:17 am
thanks, this is just what i was looking for !!
nice tutorial !
Amrita said this on April 30th, 2008 at 10:11 am
Hi,
I think the script is great. Iam atually trying to resize an image based on the inter pupil distance of both the eyes. I have written the following script which resizes but does not give me the same final inter pupil distance that I am aiming for. Iam trying to resize the images so that the target image has an inter pupil distance of 128.
Any suggestions from your side would be of great help to me.
Thank you very much
Amrita
I am pasting the script below:
Keryn said this on May 8th, 2008 at 4:57 am
Hi
I was wondering if you could help me. I had got a script working using Imagemagick and then found out the hosts had disabled exec functions due to safety reasons, fair enough but then I had to learn GD, fair enough too but I’m missing something.
Here is my original code:
# $img = “pathtoimage/image.jpg”;
# $size = GetImageSize($img);
# $dim = “300×300+0+0″;
# echo $size[0] . ” ” . $size[1];
# // Wide Image
# if($size[0] > $size[1]) {
# $thumbnail_height = 300;
# $thumbnail_width = (int)(300 * $size[0] / $size[1]);
# }
#
# // Tall Image
# else{
# $thumbnail_height = (int)(300 * $size[1] / $size[0]);
# $thumbnail_width = 300;
# }
#
# $mogrify = “pathtimagemagick/mogrify -geometry”;
# $crop = “pathtimagemagick/mogrify -gravity Center -crop”;
# system(”$mogrify $thumbnail_heightx$thumbnail_width $img”, $exec_retval);
# system(”$crop $dim $img”, $exec_retval);
and here is the GD code that I was given:
function resize_image($upload_directory, $new_image_name)
{
// original image location //
$original_image = $upload_directory;
// set up a canvas sizes //
$canvas_width = 65;
$canvas_height = 65;
// create the canvas //
$canvas = imagecreatetruecolor($canvas_width, $canvas_height);
// make the background color white //
$white_background = imagecolorallocate($canvas, 255, 255, 255);
// change the background to white //
imagefill($canvas, 0, 0, $white_background);
// get the image height and width //
list($image_width, $image_height) = getimagesize($upload_directory);
#########################################
// RATIO CALCULATIONS //
$ratio = $image_width / $image_height;
if ($ratio > 1 )
{
$new_image_width = 65;
$new_image_height = 65 / $ratio;
} else {
$new_image_width = (float) 65 * $ratio;
$new_image_height = 65;
}
// RATIO CALCULATIONS //
#########################################
// store original into memory //
$original_image = imagecreatefromjpeg($original_image);
// copy the original image onto the canvas canvas, original and top/left co-ordinates //
imagecopyresampled($canvas, $original_image, 0,0,0,0, $new_image_width, $new_image_height, $image_width, $image_height);
// thumbnail name //
$new_thumbnail_name = “thumb-$new_image_name”;
// save the thumbnail in the thumbs folder //
if(imagejpeg($canvas, “products/thumbnails/$new_thumbnail_name”, 100))
{
return(”$new_thumbnail_name”);
}
// destroy the images in memory //
imagedestroy($original_image);
imagedestroy($canvas);
} // end function //
it resizes but then it displays the image in a 300×300 canvas (not cropped) with a blank bit.
Any suggestions would be extremely appreciated
Toronto Condos said this on November 11th, 2008 at 2:47 am
Wow, Thank you for all the information guys. This is much better than going through PHP for dummies. Thank you again.
Dragan said this on December 30th, 2008 at 2:15 pm
This is clear and comprehensible. Thank you very much.
Man and Van said this on January 30th, 2009 at 8:45 am
could anyone please tell me how woyld i be able to create a new page in dreamweaver looking like this http://www.newpage.examplesite.com rather than http://www.examplesite.com/newpage.html many thanks in advance
Michael said this on April 1st, 2009 at 10:46 am
Here is nice code that will help you to resize an image without using image magic: http://superiorwebsys.com/blog/28/How_to_resize_image_with_PHP/
Re: Man and Van
what you need is to create a subdomain, and this can not be done in dreamweaver, you need to do it on the server.
How to Use PHP to Dynamically Resize an Image - Tutorial Collection said this on June 4th, 2009 at 9:25 pm
[…] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 7:59 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. […]
elandjerlet said this on July 2nd, 2009 at 9:52 am
Очень понравился ваш блог! Подписался на rss. Буду регулярно читать.