Image Resizing Made Easy with PHP

Image Resizing Made Easy with PHP

Tutorial Details
  • Estimated Completion Time: 40 minutes
  • Difficulty: Intermediate
  • Technology: PHP 5

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!


Introduction

To give you a quick glimpse at what we’re trying to achieve with our class, the class should be:

  • Easy to use
  • Format independent. I.E., open, resize, and save a number of different images formats.
  • Intelligent sizing – No image distortion!

Note: This isn’t a tutorial on how to create classes and objects, and although this skill would help, it isn’t necessary in order to follow this tutorial.

There’s a lot to cover – Let’s begin.


Step 1 Preparation

We’ll start off easy. In your working directory create two files: one called index.php, the other resize-class.php


Step 2 Calling the Object

To give you an idea of what we’re trying to achieve, we’ll begin by coding the calls we’ll use to resize the images. Open your index.php file and add the following code.

As you can see, there is a nice logic to what we’re doing. We open the image file, we set the dimensions we want to resize the image to, and the type of resize.
Then we save the image, choosing the image format we want and the image quality. Save and close your index.php file.

		// *** Include the class
		include("resize-class.php");

		// *** 1) Initialize / load image
		$resizeObj = new resize('sample.jpg');

		// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
		$resizeObj -> resizeImage(150, 100, 'crop');

		// *** 3) Save image
		$resizeObj -> saveImage('sample-resized.gif', 100);

From the code above you can see we’re opening a jpg file but saving a gif. Remember, it’s all about flexibility.


Step 3 Class Skeleton

It’s Object-Oriented Programming (OOP) that makes this sense of ease possible. Think of a class like a pattern; you can encapsulate the data – another jargon term that really just means hiding the data. We can then reuse this class over and over without the need to rewrite any of the resizing code – you only need to call the appropriate methods just as we did in step two. Once our pattern has been created, we create instances of this pattern, called objects.

“The construct function, known as a constructor, is a special class method that gets called by the class when you create a new object.”

Let’s begin creating our resize class. Open your resize-class.php file. Below is a really basic class skeleton structure which I’ve named ‘resize’. Note the class variable comment line; this is were we’ll start adding our important class variables later.

The construct function, known as a constructor, is a special class method (the term “method” is the same as function, however, when talking about classes and objects the term method is often used) that gets called by the class when you create a new object. This makes it suitable for us to do some initializing – which we’ll do in the next step.

		Class resize
		{
			// *** Class variables

			public function __construct()
			{

			}
		}

Note that’s a double underscore for the construct method.


Step 4 The Constructor

We’re going to modify the constructor method above. Firstly, we’ll pass in the filename (and path) of our image to be resized. We’ll call this variable $fileName.

We need to open the file passed in with PHP (more specifically the PHP GD Library) so PHP can read the image. We’re doing this with the custom method ‘openImage’. I’ll get to how this method
works in a moment, but for now, we need to save the result as a class variable. A class variable is just a variable – but it’s specific to that class. Remember the class variable comment I mentioned previously? Add ‘image’ as a private variable by typing ‘private $image;’. By setting the variable as ‘Private’ you’re setting the scope of that variable so it can only be accessed by the class. From now on we can make a call to our opened image, known as a resource, which we will be doing later when we resize.

While we’re at it, let’s store the height and width of the image. I have a feeling these will be useful later.

You should now have the following.

		Class resize
		{
			// *** Class variables
			private $image;
			private $width;
			private $height;

			function __construct($fileName)
			{
			    // *** Open up the file
			    $this->image = $this->openImage($fileName);

			    // *** Get width and height
			    $this->width  = imagesx($this->image);
			    $this->height = imagesy($this->image);
			}
		}

Methods imagesx and imagesy are built in functions that are part of the GD library. They retrieve the width and height of your image, respectively.


Step 5 Opening the Image

In the previous step, we call the custom method openImage. In this step we’re going to create that method. We want the script to do our thinking for us, so depending on what file type is passed in, the script should determine what GD Library function it calls to open the image. This is easily achieved by comparing the files extension with a switch statement.

We pass in our file we want to resize and return that files resource.

		private function openImage($file)
		{
		    // *** Get extension
		    $extension = strtolower(strrchr($file, '.'));

		    switch($extension)
		    {
		        case '.jpg':
		        case '.jpeg':
		            $img = @imagecreatefromjpeg($file);
		            break;
		        case '.gif':
		            $img = @imagecreatefromgif($file);
		            break;
		        case '.png':
		            $img = @imagecreatefrompng($file);
		            break;
		        default:
		            $img = false;
		            break;
		    }
		    return $img;
		}

Step 6 How to Resize

This is where the love happens. This step is really just an explanation of what we’re going to do – so no homework here. In the next step, we’re going to create a public method that we’ll call to perform our resize; so it makes sense to pass in the width and height, as well as information about how we want to resize the image. Let’s talk about this for a moment. There will be scenarios where you would like to resize an image to an exact size. Great, let’s include this. But there will also be times when you have to resize hundreds of images and each image has a different aspect ratio – think portrait images. Resizing these to an exact size will cause severe distortion.If we take a look at our options to prevent distortion we can:

  1. Resize the image as close as we can to our new image dimensions, while still keeping the aspect ratio.
  2. Resize the image as close as we can to our new image dimensions and crop the remainder.

Both options are viable, depending on your needs.

Yep. we’re going to attempt to handle all of the above. To recap, we’re going to provide options to:

  1. Resize by exact width/height. (exact)
  2. Resize by width – exact width will be set, height will be adjusted according to aspect ratio. (landscape)
  3. Resize by height – like Resize by Width, but the height will be set and width adjusted dynamically. (portrait)
  4. Auto determine options 2 and 3. If you’re looping through a folder with different size photos, let the script determine how to handle this. (auto)
  5. Resize, then crop. This is my favourite. Exact size, no distortion. (crop)

Step 7 Resizing. Let’s do it!

There are two parts to the resize method. The first is getting the optimal width and height for our new image by creating some custom methods – and of course passing in our resize ‘option’ as described above. The width and height are returned as an array and set to their respective variables. Feel free to ‘pass as reference’- but I’m not a huge fan of that.

The second part is what performs the actual resize. In order to keep this tutorial size down, I’ll let you read up on the following GD functions:

We also save the output of the imagecreatetruecolor method (a new true color image) as a class variable. Add ‘private $imageResized;’ with your other class variables.

Resizing is performed by a PHP module known as the GD Library. Many of the methods we’re using are provided by this library.

		// *** Add to class variables
		private $imageResized;
		public function resizeImage($newWidth, $newHeight, $option="auto")
		{

			// *** Get optimal width and height - based on $option
			$optionArray = $this->getDimensions($newWidth, $newHeight, strtolower($option));

			$optimalWidth  = $optionArray['optimalWidth'];
			$optimalHeight = $optionArray['optimalHeight'];

			// *** Resample - create image canvas of x, y size
			$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
			imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);

			// *** if option is 'crop', then crop too
			if ($option == 'crop') {
				$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
			}
		}

Step 8 The Decision Tree

The more work you do now, the less you have to do when you resize. This method chooses the route to take, with the goal of getting the optimal resize width and height based on your resize option. It’ll call the appropriate method, of which we’ll be creating in the next step.

		private function getDimensions($newWidth, $newHeight, $option)
		{

		   switch ($option)
		    {
		        case 'exact':
		            $optimalWidth = $newWidth;
		            $optimalHeight= $newHeight;
		            break;
		        case 'portrait':
		            $optimalWidth = $this->getSizeByFixedHeight($newHeight);
		            $optimalHeight= $newHeight;
		            break;
		        case 'landscape':
		            $optimalWidth = $newWidth;
		            $optimalHeight= $this->getSizeByFixedWidth($newWidth);
		            break;
		        case 'auto':
		            $optionArray = $this->getSizeByAuto($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
		            break;
				case 'crop':
		            $optionArray = $this->getOptimalCrop($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
		            break;
		    }
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

Step 9 Optimal Dimensions

We’ve already discussed what these four methods do. They’re just basic maths, really, that calculate our best fit.

		private function getSizeByFixedHeight($newHeight)
		{
		    $ratio = $this->width / $this->height;
		    $newWidth = $newHeight * $ratio;
		    return $newWidth;
		}

		private function getSizeByFixedWidth($newWidth)
		{
		    $ratio = $this->height / $this->width;
		    $newHeight = $newWidth * $ratio;
		    return $newHeight;
		}

		private function getSizeByAuto($newWidth, $newHeight)
		{
		    if ($this->height < $this->width)
		    // *** Image to be resized is wider (landscape)
		    {
		        $optimalWidth = $newWidth;
		        $optimalHeight= $this->getSizeByFixedWidth($newWidth);
		    }
		    elseif ($this->height > $this->width)
		    // *** Image to be resized is taller (portrait)
		    {
		        $optimalWidth = $this->getSizeByFixedHeight($newHeight);
		        $optimalHeight= $newHeight;
		    }
			else
		    // *** Image to be resizerd is a square
		    {
				if ($newHeight < $newWidth) {
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				} else if ($newHeight > $newWidth) {
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
				    $optimalHeight= $newHeight;
				} else {
					// *** Sqaure being resized to a square
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
				}
		    }

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

		private function getOptimalCrop($newWidth, $newHeight)
		{

			$heightRatio = $this->height / $newHeight;
			$widthRatio  = $this->width /  $newWidth;

			if ($heightRatio < $widthRatio) {
				$optimalRatio = $heightRatio;
			} else {
				$optimalRatio = $widthRatio;
			}

			$optimalHeight = $this->height / $optimalRatio;
			$optimalWidth  = $this->width  / $optimalRatio;

			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}

Step 10 Crop

If you opted in for a crop – that is, you’ve used the crop option, then you have one more little step. We’re going to crop the image from the
center. Cropping is a very similar process to resizing but with a couple more sizing parameters passed in.

		private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
		{
			// *** Find center - this will be used for the crop
			$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
			$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

			$crop = $this->imageResized;
			//imagedestroy($this->imageResized);

			// *** Now crop from center to exact requested size
			$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
			imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
		}

Step 11 Save the Image

We’re getting there; almost done. It’s now time to save the image. We pass in the path, and the image quality we would like ranging from 0-100, 100 being the best, and call the appropriate method. A couple of things to note about the image quality: JPG uses a scale of 0-100, 100 being the best. GIF images don’t have an image quality setting. PNG’s do, but they use the scale 0-9, 0 being the best. This isn’t good as we can’t expect ourselves to remember this every time we want to save an image. We do a bit of magic to standardize everything.

		public function saveImage($savePath, $imageQuality="100")
		{
			// *** Get extension
        	$extension = strrchr($savePath, '.');
        	$extension = strtolower($extension);

			switch($extension)
			{
				case '.jpg':
				case '.jpeg':
					if (imagetypes() & IMG_JPG) {
						imagejpeg($this->imageResized, $savePath, $imageQuality);
					}
		            break;

				case '.gif':
					if (imagetypes() & IMG_GIF) {
						imagegif($this->imageResized, $savePath);
					}
					break;

				case '.png':
					// *** Scale quality from 0-100 to 0-9
					$scaleQuality = round(($imageQuality/100) * 9);

					// *** Invert quality setting as 0 is best, not 9
					$invertScaleQuality = 9 - $scaleQuality;

					if (imagetypes() & IMG_PNG) {
						imagepng($this->imageResized, $savePath, $invertScaleQuality);
					}
					break;

				// ... etc

				default:
					// *** No extension - No save.
					break;
			}

			imagedestroy($this->imageResized);
		}

Now is also a good time to destroy our image resource to free up some memory. If you were to use this in production, it might also be a good idea to capture and return the result of the saved image.


Conclusion

Well that’s it, folks. Thank you for following this tutorial, I hope you find it useful. I’d appreciate your feedback, via the comments below.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://felixb.se/ Felix

    Thanks for this one!

  • http://www.go-shape.com Daniel Bidmon

    Very cool, thank you!

  • Akshay Aurora

    So much in habit of watching Screencasts, just don’t feel like reading it.

    Anyways looks like another gr8 NetTuts tutorial.

    • oconn96

      Not everything is served on a silver platter. Sometimes reading is the best way to learn, and can be done at your own pace.

      • theFlashman

        whoa……… whats with the remark, the guy was just saying his own learning method, and here you are mister so called mighty one with your fancy words like silver and reading.

        keep your slating to yourself.

        Its pointless trying to come up with a reply………i’m already gone.

        Great tut+

    • jack

      your such an ass.

      boo-hoo I am used to having info shoved in my brain…..I cant be bothered to ….oh gosh…you know…the R-E-A-D word anything.

      • http://www.paulchater.co.uk Paul Chater

        I don’t think that the guy was slating anybody,

        He was simply just implying that he couldn’t be bothered reading it and that he was used to watching the screencasts as there has been a lot of them on the Tuts+ network lately. I don’t believe he was trying to be an “ass” at all. In fact, the only “ass” here would be the yourself and @oconn96.

    • http://www.tastybytes.net Brian

      I would much prefer a written tutorial than a screen cast…

      I skimmed and picked up the needed parts in under 2 minutes.

      I can almost guarantee that a screen cast of this same tutorial would have taken at least 20 or 30 minutes to watch him type it all out (BORING) …

  • Nathan II

    Cool! I have been looking for a way to do this in PHP in case I ever need to know how…and this makes it much more simple. I primarily use ColdFusion and it has some pretty sweet built-in functions for image resizing!

  • http://www.smple.com John McMullen

    Thumbs up from me. Pretty rocking tutorial. Great explanations.

  • http://www.xdee.net Michael

    Great Tutorial, exactly what I needed!
    BTW I like that you’re working with Linux ;-)

  • Peter

    Thanks for the article! Really helpful and clear!

  • http://chrisbauer.org Chris Bauer

    Horray for the Ubuntu Dust theme! I thought I was looking at screenshots of my computer at first.

    • Bluenote

      +1 ! ;D

  • http://www.snoupix.com/ Stephane

    Thanks, great tutorial.

  • http://www.avey.de Way

    Congrats to your first nettuts tutorial Jarrod Oberto ;)
    I really like it. Good and clean code with nice writing and explanation. Keep it going!

    • Jarrod Oberto
      Author

      Cheers dude.

  • http://micheletitolo.com Michele

    Great tutorial! With the way it’s broken down, this is a good introduction to OOP as well! I think it would be really useful to see more tutorials written like this in the future.

    • http://twitter.com/montanaflynn Montana Flynn

      I was thinking the same thing.

  • http://www.pixelsoul.com pixelsoul

    Tutorials like this are why I always come back to Nettuts to see what is new. Good job.

  • http://www.visualisations.co.nz Pieter V

    What needs to be added to this to support alpha channels? or will it do it as is?

  • http://360signals.com Maor

    Thanks for the great tutorial!

  • http://www.patriciopalladino.com alcuadrado

    Nice article, but don’t forget Imagick extension: http://php.net/imagick

    • http://www.compasscreative.ca/ Jonathan

      ImageMagick (http://www.imagemagick.org/) is a great alternative to the GD library, however, it’s not as likely to be installed by default on a web server. You don’t necessarily need the PHP extension for it either – I personally just execute commands using the PHP system function (http://www.php.net/manual/en/function.system.php). For example:

      system(‘convert original_image.jpg -resize 150×150 -quality 95 thumb.jpg’);

      That simply resizes your original file to a maximum width & height of 150px and saves it as thumb.jpg.

      Thanks for this article Nettuts!

  • http://www.enciende.cl EmpreJorge

    Great tut, easy to follow :D.
    Is there any problem with animated gif??, I haven’t try it yet.
    Thanks :)

  • George

    Thank you for this perfect tutorial

  • http://wpcanyon.com Slobodan Kustrimovic

    Nice :) I remember back then when i was starting with php i was battling with resizing images, needed few hours to figure it out because there wasn’t any good tutorials on how to do it and the ready made functions ware crappy (long time ago).

  • Chris

    Very nice, thanks for the tut.

  • dave

    Looks fun, personally I would rather do this

    hell, you could use the free open-source Railo cfm engine (http://www.getrailo.org/) and be able to convert videos as well with one line of code:

  • oconn96

    I love how nettuts+ always knows what I am thinking. I was looking this up yesterday then I come on here today and I have this awesome tutorial on how to do it waiting for me. You did a really nice job explaining everything. I only read about half way, too much discrete math homework that needs to get done by tomorrow.

  • http://www.cbesslabs.com Sebastian Bratu

    Cool one, I always had a bug in gif and png formats in my own resize library, which I never had time to fix.

  • Nicolas

    Really usefull, thank you!

  • http://stevendobbelaere.be Steven Dobbelaere

    I’m more fond of this approach http://shiftingpixel.com/2008/03/03/smart-image-resizer/
    This resizes images on the fly, without having to crop in advance.

  • Harro

    Don’t use this if you have big photo’s on a big website. You’ll run out of memory. GD2 loads all the images into PHP memory which can cause issues.

    We use the Imagick extension, it’s faster and uses less memory.

    • http://blendfresh.net Nk

      I agree 100%, ImageMagick is much better than GD. Also, a lot of the time GD isn’t installed or enabled with a standard PHP install.

      • http://www.edfuh.com Ed

        I also agree, Imagick is way better. But it’s a pain to install on shared hosting.

  • Tom

    We’re also using the shiftingpixel.com script. It’s good becasue it’s very quick, and creates a cache file. Also has a lot of extra functionality like image sharpening etc.

  • http://stvproductions.net Thomas

    This is comming in so handy! Just needed something like this for a project. Thank you. You’re a life saver!!

  • http://www.bestfreewebresources.com/ BBL

    useful tut

  • http://sonergonul.com/ Soner Gönül

    Nice and useful post

    Thank you..!

  • http://www.jordanwalker.net Jordan Walker

    Great tutorial about resizing images.

  • jonathan dusza

    any chance of having this upload an image to create the new ‘sample-resized’ ?

  • Michael

    Awesome, thx a lot! Waited a long time for a good cropping solution.

  • http://spotdex.com Davidmoreen

    Great article, and as I said before, every time I need something that I have never done before in a project nuttuts publishes a tutorial on it. I think you guys are reading my brain!

  • SimpleUser

    looks great, but this script doesn’t work correctly with png+alphachanel
    http://my.jetscreenshot.com/4/20100319-51t2-23kb

  • http://www.wizone.se Wadman

    Loving the tutorial! This will definitely be of good use!

  • http://godsea.adicto.org Jordi Rivero

    Nice and useful post. Thanks!

  • http://cubelabs.net Rashid

    Exceptional tutorial. Five stars.

  • http://danielbdesigns.com Daniel

    Finally! Someone shows off that they are using Ubuntu.

  • julie

    hello,

    I try to apply a watermark on the image cross but it does not appear if I did this:

    public function resizeImage($newWidth, $newHeight, $option=”auto”)
    {
    // *** Obtenir la largeur et la hauteur optimale – sur la base $ option
    $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

    $optimalWidth = $optionArray['optimalWidth'];
    $optimalHeight = $optionArray['optimalHeight'];

    // *** Rééchantillonnage – créer des canevas de l’image de x, y taille
    $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);

    // *** Recupere les dimentions
    $size = getimagesize($this->imageResized);

    // *** Applique le filigramme croisé sur l’image
    $font = “applegaramond-bold.ttf”; // Police utilisée pour écrire le filigrane
    $filigrane = “Copyright”;
    $t=20; // Taille de la police
    $couleur_text = imagecolorallocatealpha($this->imageResized, 255, 255, 255, 75);

    $h=0;
    $l=0;
    $i=0;
    //Cette double boucle permet de répeter le filigrane en croisé sur toute l’image (suivant sa taille)
    while($h<$size[1])
    {
    while($limageResized, $t, 0, $l, $h+$t, $couleur_text, $font, $filigrane);
    $l=$l+400;
    }

    $i++;
    if($i % 2){$l=200;}else{$l=0;}
    $h=$h+100;
    }

    imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
    }

    The goal is to obtain a similar result:
    http://rrr.favrat.net/?p=26

    Someone an idea ?

    thank you for your help

  • Dom

    This my friend is totally awesome!

  • http://www.paulchater.co.uk Paul Chater

    Personally, I haven’t quite read this tutorial, rather just skimmed over it; but it looks as though it could be rather handy later on.

    I shall have to read this more later when i’m not that tired. But yeah, good work :) It’s actually nice to see some text tutorials coming even if they have been lengthy hehe. But I suppose that’s all the fun ;)

  • http://niks-blog.info Nik

    nice tut)i’ve searched billions of scripts to integrate to our portfolio cms.that’s what we really need)thx a lot!

  • sujata likhar

    its very useful and very clear …….

  • http://reenaverma.wetpaint.com reena verma

    Tu Jo Nahi Hai Toh Kuch Bhi Nahee Hai

  • Gobezu

    Nice tut if you must use bare php. If you afford to add some php classes then I would suggest to use any of the excellent libraries available, ex. http://wideimage.sourceforge.net/

  • http://rstankov.com Radoslav Stankov

    Good tutorial, but I there are some little things in the code I didn’t like. I was starting to write a comment but they were many so I wrote a blog post – http://next.pixeldepo.com/2010/03/24/image-resizing-%D1%81-php/ ( plus I make some code clean up here – http://gist.github.com/342704/ )

  • dtroup

    This is a great class!

    I had a question on how to run this 2x on the same image.

    include(“resize-class.php”);

    $resizeObj = new resize(‘sample.jpg’);
    $resizeObj -> resizeImage(150, 100, ‘crop’);
    $resizeObj -> saveImage(‘sample-resized.gif’, 100);

    $resizeObj2 = new resize(‘sample.jpg’);
    $resizeObj2 -> resizeImage(410, ‘landscape’);
    $resizeObj2 -> saveImage(‘sample-resized2.gif’, 100);

    I tried it and it only seems to do the first. Any insight on running this on multiple images or multiple times on one image would be great.

    Thanks!

    • ran_dizolph

      AFAIK, you don’t need to change the name for calling the resizeObj when you want to use it multiple times on one page.

      I’ve set it up to crop a big image down, then create a thumbnail using following…it’s for a dynamic image uploader on a website, but you get the idea.
      // *** Include the class
      include(“resize-class.php”);

      // *** 1) Copy original file to server
      copy($_FILES['photo']['tmp_name'], $upload_dir.”".$_FILES['photo']['name']);
      // *** 2) Initialise / load image
      $resizeObj = new resize($upload_dir.”".$_FILES['photo']['name']);
      // *** 3) Resize image (options: exact, portrait, landscape, auto, crop)
      $resizeObj -> resizeImage(240, 300, ‘crop’);
      // *** 4) Create filename, and Save image
      $member_id = 311;
      $filename = $member_id.”_”.time().”.jpg” ;
      $resizeObj -> saveImage($upload_dir.”".$filename, 100);

      // *** THUMBNAIL CREATION

      // *** 5) Initialise / load image
      $resizeObj = new resize($upload_dir.”".$filename);
      // *** 6) Resize image (options: exact, portrait, landscape, auto, crop)
      $resizeObj -> resizeImage(100, 125, ‘crop’);
      // *** 7) Rename the file for thumbnail, and save it
      $thumbname = “tb_”.$filename ;
      $resizeObj -> saveImage($upload_dir.”".$thumbname, 100);

      // *** END THUMBNAIL CREATION

      // *** 8) Remove original file
      unlink($upload_dir.”".$_FILES['photo']['name']) ;

  • ran_dizolph

    Fantastic stuff…thanks for sharing this!

  • Josh

    Is there is file size limit on this? I can seem to get it work with some images that are over a MB

  • webcook

    Thanks really superb