PHP: Resize Image and Store to File

by Yang Yang on January 15, 2009

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.

Subscribe to Kavoir: blog feed

You should also read:

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

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.

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

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.

WILLIAMPGH March 21, 2011 at 1:53 am

You need to set the file folder in windows to share to upload files to it. If the folder is not to set to share on your system, you can not upload files cause the file folder is set to read only if you do not share the folder. Just a heads up. =)

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

Yang Yang September 26, 2009 at 6:46 pm

That it is. Thanks a lot, Boris!

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

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. :)

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!

Yang Yang March 17, 2010 at 3:29 pm

Thank you for your compliments, Jillian!

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!

Yang Yang April 19, 2010 at 3:55 pm

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

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.

Yang Yang May 13, 2010 at 10:42 pm

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

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?

Yang Yang July 28, 2010 at 8:28 am

Try changing the single quotes to double quotes:

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

Kim Hoe December 8, 2010 at 12:36 pm

Hi,

I couldn’t get this work. Please can you check for me? No Error is given.

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
}
}

?>

resize(400, ’104246094_400.jpg’);
?>

Kim Hoe December 8, 2010 at 1:51 pm

Sorry, I think the copy and paste working well.

Here is the script that I use to call the function:

$work = new ImgResizer(’104246094.jpg’);
$work -> resize(400, ’104246094_400.jpg’);

EricC February 24, 2011 at 2:41 am

Nice, and far better with the switch cases added by Greg.
Plus, this code is more or less useless for me, the old file being overwritten by the new one :
if (file_exists($targetFile)) {
unlink($targetFile);
}

Kieuw- August 27, 2011 at 8:06 pm

Thanks all the way from Puerto Rico! It is awesome! Thanks!

Mike Clayton November 8, 2011 at 4:25 am

Great script. By far the quickest-to-use script for image resizing I have found yet!!!!!

Etienne May 23, 2012 at 2:20 pm

Thank you!!

parttimenerd July 1, 2012 at 7:16 pm

Your code was a great help for me (I tried to use the convert.exe by ImageMagick before without success).
I’ve modified your code a bit, to cope with some other file extensions:

function resizeImage($newWidth, $originalFile, $targetFile = “”) {
$exts = array(“jpeg”, “bmp”, “png”, “gif”);
if (empty($newWidth) || empty($originalFile) || !in_array(pathinfo($originalFile, PATHINFO_EXTENSION), $exts)) {
return false;
}
if ($targetFile = “”){
$targetFile = $originalFile;
} else if (!in_array(pathinfo($targetFile, PATHINFO_EXTENSION), $exts)){
return false;
}
$func = “imagecreatefrom” . pathinfo($originalFile, PATHINFO_EXTENSION);
$src = $func($originalFile);
list($width, $height) = getimagesize($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);
}
$ext_target = pathinfo($targetFile, PATHINFO_EXTENSION);
$func = “image” . $ext_target;
$func($tmp, $targetFile, $env->pic_quality);
return true;
}

Rolf February 7, 2013 at 7:18 am

Great code. Thanks! One question: when a jpg is uploaded by an iPhone, it contains an ‘orientation’. When the images is resized, the orientation is lost. Result is a rotated image. Any idea how to test for that and rotate the image?

Comments on this entry are closed.

{ 3 trackbacks }

Previous post:

Next post: