Advanced image resizing in PHP

advanced image resize in PHPPHP has some nice features for resizing and modification of images. In this post we’ll build a script that can take local or remote images, resize the images based on a bounding box, and optimize the files, so the file size gets as small as possible.

The script saves the resized and optimized images as jpg files.

This script can be very useful if you wants to automate downloading and optimization of external images, or has a big collection of images that needs to be resized.

Resizing issues

The idea behind this script came when I was importing images from multiple remote resources for a new website. The images were all in different sizes and most important in different proportions. Some of the images were tall while others where very wide.

Handling images with diffeernt sizes and proportions in php

Since the images should were displayed next to each other, the normal resizing to a certain with or height wasn’t useful, since the different proportions of the images made the page look very strange.

Bounding box resizing

The solution was to develop a script that resized the image to the biggest size, that fits within a bounding box. The bounding box defines the maximum with and height that you want to allocate for  the images in your design.

Image resizing i PHP based on bounding box

When you optimize images based on a bounding box, you can control the layout of your page, since no images will break the bounding box that you have specified.

Given the difference that might be between your bounding box and the proportions of the original images, there might be some “open space” in you bounding box, but if you don’t want to resize and crop all images yourself, I think you’ll find the bounding box method pretty useful.

The image resize script

The PHP script or function to be more accurate, needs to be called with a url for the original image, and a file name for the destination image. In the function you need to configure the following variables:

  • $max_width. The maximum width of the resized image in pixels
  • $max_height. The maximum height of the resized image in pixels
  • $destination. The destination for the resized image. Depending on your server configuration it could be something like this:  “/var/www/mysite.com/img/resized/”
  • $quality. How much should the image be compressed. The amount of compression normally depends on the size of the resized image. The bigger image, the moderate you have to be with the compression. Normally a compression around 80 is fine. Which means that the resized image will be compressed to 80% of the original resized file size. The compression value needs to be a number between 0 and 100
<?
function download_product_screenshot($url, $filename) {
 $max_width = 100;
 $max_height = 100;
 $destination = '[insert the destination of the resized image here]';
 $quality = '[insert the quality of the resized imgage]';
 $source_pic = ''.$url.'';
 $src = imagecreatefromjpeg($source_pic);
 list($width,$height)=getimagesize($source_pic);

 $x_ratio = $max_width / $width;
 $y_ratio = $max_height / $height;

 if( ($width <= $max_width) && ($height <= $max_height) ){
   $tn_width = $width;
   $tn_height = $height;
 } elseif (($x_ratio * $height) < $max_height){
   $tn_height = ceil($x_ratio * $height);
   $tn_width = $max_width;
 } else {
   $tn_width = ceil($y_ratio * $width);
   $tn_height = $max_height;
 }

 $tmp=imagecreatetruecolor($tn_width,$tn_height);
 imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
 $destination_pic = ''.$destination.'/'.$filename.'.jpg';
 imagejpeg($tmp,$destination_pic,$quality);
 imagedestroy($src);
 imagedestroy($tmp);
}
?>

The results

So what kind of quality can a script like this provide? Let me show a real life example. For my website I needed to import images from 2 different sources with different proportions. The images were resized to fit within a 100×100 pixels bounding box.

As you can see form the table below the resize script has reduced the file size significant, and at the same time automatically maximized the image size within the bounding box.
PHP image resize results
Just as important, the images now fits nice into the 100×100 display box that I have on my website.
images after resize based on a bounding box

If the images hasn’t been resized within a bounding box the different proportions of the images could break the nice layout.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

2 Replies to Advanced image resizing in PHP

  1. Bob says:

    Hi,

    First off, Thanks for posting your work!

    Looking at the script above, does it work if the bounding box isn’t square? I’ve written a script that does the same as above for a square ‘bounding box’ (basically resizing to a maximum longest edge) but if you start changing the bounding box to something more obscure (for example 1024 x 768) then mine breaks in some instances (for example an a landscape image that is still closer to potrait than 1024×768 will resize based on width to 1024 but its height will be greater than 768 to it breaks the box). I’m trying to work up an elegant set of logic now but was hoping someone else had already done it!

    Also one quick thing to note, in the example above, if the image is bigger than both max X and max Y (ie, the first IF is true) does the script resize it to exactly fit the bounding box, breaking the aspect ratio of the image?

    I confess I’m not a PHP developer so I’m reading this as a layman.

    Bob

  2. Frank E. says:

    I want to thank you for writing and posting excellent code. I am not well verse in PHP but I do know code and especially good code. In developing my own resizing script I found myself looking more at this sample for a few reasons. First, your code does not allow an image to be enlarged. Most image resizing code I’ve looked at is flawed in that respect.

    For example, if I set a max width of 320px wide but feed the code an image only 300px wide, most code will enlarge the image to max size, which is, well, pretty stupid. Your code adds an extra if-else which first tests the size of the image against the maximum, and leaves it untouched if at or below the max. This is simple but well thought out, and missing in all the other code I looked at.

    Another cool thing I like about your code is the flexibility. If I want a set of photos to be all the same width, or height, then I can simply enter max dims like this: 320px max width, 20000px max height. Since o image would ever hit the max height, this trick will yield a set of images all the exact same width. No change to the code, just changing one variable.

    So, I’ve “borrowed” some of your ideas and built them into my resizing script. I’ve thrown in a few filters, especially for thumbnails, which tend to go blurry, so I added some sharpening and contrast adjustments.

    But, I wanted to personally thank you for sharing excellent, compact and powerful code that seems to blow away most other I’ve looked at for this purpose, and I’ve looked at a ton of code. This is among the tops for this purpose. Thanks for that.

Comments are now closed for this article.