PHP Image Resizing

In this tutorial, I’ll quickly go over how to resize images with PHP. To do so is pretty simple: Open the image to be resized, create a new image of the new size, and copy the resampled image over.

The Code

header(‘Content-type: image/jpeg’);
list($w, $h) = getimagesize($filename);

$resized = imagecreatetruecolor($width, $height);
$original = imagecreatefromjpeg($filename);
imagecopyresampled($resized, $original, 0, 0, 0, 0, $width, $height, $w, $h);

imagejpeg($resized, null, 100);

To use this script, you’d use it something like resize.php?filename=myphoto.jpg&width=120&height=75. Note that you’d want to do some sort of check on the input but for the sake of this tutorial this is fine.

The first two lines are simple: You are telling the browser what to expect, and getting the width ($w) and height ($h) of the original image.

The next three lines are the core of what is going on. You are creating a new image with the new width and height, and opening the original image.

imagecopyresampled is then used. All the zeros are setting the top and left image pointers to the top left corner. If you want, you can resize a cropped section of the image by changing the second set of zeros. You can also put the resized image within a section of the new image by changing the first set of 0’s.

And of course the last 4 inputted values are the new sizes and old sizes. You could also change these if you want to crop or resize within an image.

We end it out by creating the jpeg image and outputting it to the browser.