PHP: Resize Image and Store to File

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.

28 comments

  1. Frank

    Yang Yang,

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

    Frank

  2. dave_ddc

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

  3. Nathan

    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

      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

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

  4. boris

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

    • Yang Yang

      That it is. Thanks a lot, Boris!

  5. Rob Web Design Talk

    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

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

  6. Pingback: PHP Image Resize script - Resize Images on the fly

  7. Jillian

    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

      Thank you for your compliments, Jillian!

  8. Greg

    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

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

  9. Josep

    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

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

  10. Jason

    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

      Try changing the single quotes to double quotes:

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

  11. Kim Hoe

    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’);
    ?>

  12. Kim Hoe

    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’);

  13. EricC

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

  14. Kieuw-

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

  15. Mike Clayton

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

  16. Pingback: PHP: Get Mime Type of a File (and Encoding)

  17. Etienne

    Thank you!!

  18. parttimenerd

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

  19. Pingback: 5+ ways to resize Image in Php | Tuts Magazine | tutorials Magazine for Web Designers and Developers

  20. Rolf

    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?