Image Resizing Code based on Width & Height in PHP

Code Sport 16 Sep , 2013  


Hi All. Ever wanted an all purpose, easy to use method of resizing your images in PHP? Well that’s what PHP classes are for – reusable pieces of functionality that we call to do the dirty work behind the scenes. We’re going to learn how to create our own class that will be well constructed, as well as expandable. Resizing should be easy. How easy? How about three steps!

Let’s say we have a Products listing page & various food products are listed with its thumbnail images like Cheese packet, Honey Bottle, Tea packets etc. These products are not supposed to be having all same size images. But we have to show that as thumbnail with proper resolution.

Image resize with PHP

So here is what we can do to achieve it easily.
1. Decide the maximum image width & height
2. Include the function code below into your code & call it like this where you want to display the image

<? echo imageRestrict($image, $maxwidth, $maxheight) ; ?>

$image = Path of the original image
$maxwidth = maximum width decided for the image
$maxheight = maximum height decided for the image


As you can see, this was a very simple 2 step task to do. The way this function will work is, it will first decide the New height of the image Based on the Maximum Width.

function imageRestrict($image, $maxwidth, $maxheight) {

list($width,$height) = getimagesize($image);

if ($width > $maxwidth) {

$newheight = $maxwidth/$width * $height;

if($newheight > $maxheight){
$maxwidth = ($maxheight * $maxwidth)/$newheight;
$newheight = $maxheight;

return '<img src="'.$image.'" width="'.$maxwidth.'" height="'.$newheight.'">';


else {

return '<img src="'.$image.'" width="'.$width.'" height="'.$height.'">';



After that it will check if the New Height goes beyond the Maximum height, then it will calculate the Maximum Width based on the New Height. This way it will calculate both Height & the Width to fit in the decided Maximum Height/Width.

or you can also do this by the help of following code


// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output

So guys I hope these peace of code gets helpful for you in coding. Leave a comment if you like this post.

, , ,