PHP: Resize Image and Store to File

by Yang Yang on January 15, 2009

in Free PHP Classes & Library,PHP Tips & Tutorials

While there are a lot of methods for you to resize images with php, we will be using extension gd this time. Make sure you or your hosting company has installed it in the php distribution by running

<?php
if (extension_loaded('gd')) { // return true if the extension’s loaded.
	echo 'Installed.';
} else {
	if (dl('gd.so')) { // dl() loads php extensions on the fly.
		echo 'Installed.';
	} else {
		echo 'Not installed.';
	}
}
?>

If the output is ‘Installed.’, let’s proceed to resize some images in php.

This image resize script is meant for shot photos because it works better with bitmap images such as .jpg and .bmp. If you need to keep transparency in the output, the code below will not help you.

PHP Resize Image Class

Basically, this class is created with the source image ($originalFile, the full path to the image) to be resized. When you initiate method resize() which takes in 2 parameters, new width ($newWidth) and the target file ($targetFile, full path to the destination image file) that would be storing the resized image, it goes like this:

  1. Get the original width and height of the image.
  2. Calculate the new height given the new width – you could easily tweak the code yourself to resize the image by a new height.
  3. Resize the image by the help of gd.
  4. Store the resized image in $targetFile, optionally erasing the old file before dumping the data because chances are you just want to resize the image and don’t need the old version anymore. However, if it’s just a temporary resize, make $targetFile different from $originalFile.
Class (PHP5):
class ImgResizer {
	private $originalFile = '';
	public function __construct($originalFile = '') {
		$this -> originalFile = $originalFile;
	}
	public function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		}
		$src = imagecreatefromjpeg($this -> originalFile);
		list($width, $height) = getimagesize($this -> originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
			unlink($targetFile);
		}
		imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious
	}
}
Class (PHP4):
class ImgResizer {
	var $originalFile = '';
	function ImgResizer($originalFile = '') {
		$this -> originalFile = $originalFile;
	}
	function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		}
		$src = imagecreatefromjpeg($this -> originalFile);
		list($width, $height) = getimagesize($this -> originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
			unlink($targetFile);
		}
		imagejpeg($tmp, $targetFile, 85);
	}
}
Class usage
<?php

$work = new ImgResizer('img/me.jpg'); // me.jpg (800x600) is in directory ‘img’ in the same path as this php script.
$work -> resize(400, 'img/me.jpg'); // the old me.jpg (800x600) is now replaced and overwritten with a smaller me.jpg (400x300).

// To store resized image to a new file thus retaining the 800x600 version of me.jpg, go with this instead:
// $work -> resize(400, 'img/me_smaller.jpg');

?>

As I have said, you might want to resize the image by a new height and calculate the width instead of going the other way around as I’ve done thus far, and it’s easy to make your tweak in the class above because height and width are fundamentally the same in dimensions, and no one’s more privileged over the other.

Related Posts

{ 16 comments… read them below or add one }

Frank July 2, 2009 at 6:23 am

Yang Yang,

Thank you for a simple and well commented class example.
It works really well!

Frank

Reply

dave_ddc July 7, 2009 at 9:56 pm

Very nice! Thanks for an introduction to this powerful extension, and for providing an excellent example class.

Reply

Nathan September 3, 2009 at 3:35 am

I am running into some trouble…sorry for commenting on an old post but I would love to be able to use this awesome script. Unfortunately I keep receiving this error, and not being a php expert I am unsure of what I am doing wrong.

Warning: imagejpeg() [function.imagejpeg]: Unable to open ‘picture2.jpg’ for writing: Permission denied in C:\**\**\**\**\**\index.php on line 39

This is what line 39 looks like

imagejpeg($tmp, $targetFile, 85);

I just copied your example and changed the images which are located in the same directory as the file calling them so I did this

$work = new ImgResize(‘picture.jpg’);
$work -> resize(400, ‘picture2.jpg’);

Any help would be greatly appreciated!

Thanks!

Nathan

Reply

Yang Yang February 26, 2010 at 4:17 pm

Seems to be a permission-related problem of your system, no idea what could be done to solve it though. Never had any combat experience with Windows system in web development.

Reply

boris September 26, 2009 at 4:08 am

Yang,
The code is fine beside a typo. You call your class ImgResizer, but create an instance ImgResize instead.
Thanks,
Boris

Reply

Yang Yang September 26, 2009 at 6:46 pm

That it is. Thanks a lot, Boris!

Reply

Rob Web Design Talk November 19, 2009 at 3:35 am

Excellent class – simple to use and works very well. Might be useful add an extra arguement to not overwrite the original file?

Many Thanks

Reply

Yang Yang November 24, 2009 at 10:28 am

Specify an output file name other than the original file name and the original one will not be overwritten. :)

Reply

Jillian March 17, 2010 at 3:15 am

This is a beautiful class. Most of the time when I take code from the web, it takes a while to debug, but your stuff worked without any modification. Thanks for posting this!

Reply

Yang Yang March 17, 2010 at 3:29 pm

Thank you for your compliments, Jillian!

Reply

Greg April 19, 2010 at 4:13 am

Excellent coding. Did the same, took the coding straight from the page, and it worked flawlessly.

I did a bit of modification though that might help someone.

Added to: public function resize($newWidth, $targetFile, $ext)

This is a previously tested string that could be ‘jpg’, ‘gif’, or ‘png’.

Then I replaced the one imagefromjpeg with:
switch ($ext) {
case “jpg”:
$src = imagecreatefromjpeg($this -> originalFile);
break;
case “gif”:
$src = ImageCreateFromGif($this -> originalFile);
break;
case “png”:
$src = ImageCreateFrompng($this -> originalFile);
break;
}

And lastly, replaced the imagejpeg() with:

switch ($ext) {
case “jpg”:
imagejpeg($tmp, $targetFile, 80);
break;
case “gif”:
imagegif($tmp, $targetFile);
break;
case “png”:
imagepng($tmp, $targetFile, 8);
break;
}

So far, testing has worked well with all three types of files. Obviously it’ll break some, like animated Gifs, but given my application that wasn’t a deal breaker.

Thanks Yang!

Reply

Yang Yang April 19, 2010 at 3:55 pm

Thanks, Greg. That’s a nice upgrade to the class!

Reply

Josep May 13, 2010 at 1:11 am

Thank you very much Yang Yang for this class,

I was searching on Google one easy method for image resizing with PHP and, all other that I found are very extensive and complicated.

Thanks for your contribution to the PHP world and greetings from Spain!

Josep Crespo.

Reply

Yang Yang May 13, 2010 at 10:42 pm

It feels so great to have helped people like you, Josep. :)

Reply

Jason July 27, 2010 at 11:03 am

First off, thank you for a wonderful class.

Second: I can’t seem to get it to work when using a $variable for the original image name.

e.g. private $originalFile = ‘uploads/thumb/$img’;
where $img = ‘asdf.jpg’;

Any pointers?

Reply

Yang Yang July 28, 2010 at 8:28 am

Try changing the single quotes to double quotes:

private $originalFile = “uploads/thumb/$img”;

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: