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://www.mudin.net mudin

    Oh very good, thank you for tutorials.. this very useful for my projects..

  • tutkun

    Thank you very much!

  • WF

    I am using the original download (version 1.0 released 17-Jan-10) and everything works perfectly (thanks by the way…this looks like it will be very useful). i tested it on a variety of small/normal jpg images. My problem came when i tried it on a very large (12mega-pixel) image just for grins. My upload script successfully got the file onto my server (no file-size issues) but when it gets to the portion of the code that used this class, i end up on a blank screen. It seems that somewhere the class is failing (presumably due to the large file-size and either a php or apache configuration i need to change or other issue)…but there is no error message or anything else thrown from the class. What can i do to detect whether the re-size was successful? I am okay with just displaying an error message…i understand that it is a bit extreme to expect the server to re-size such a large image…i just need to know how to generate an error so i can warn the user appropriately. Thanks!!

    • James

      Have the same problem using this class and temporary fixed it by setting a limit of 4 MB to the picture.

      You could do somehing like:

      $srcOfFile = “myRelativePath/file.jpg”
      $fileSize = filesize($srcOfFile);

      if($fileSize > 4194304){ // Bigger than 4 MB
      echo “ERROR”;
      } else{
      // Use this class for resizing
      }

      If anyone has a solution that also provides big images to resize, please let me know.

    • James

      I found a solution:

      “=> memory_limit : Maximum amount of memory a script may consume (default 8MB)”

      You have to overwrite this default value either by Htaccess:

      - “RewriteEngine on
      - php_value memory_limit 200M”

      or in the php.ini file..

      • WF

        Thanks! I will give that a try.

    • http://bart-art.cz Lubomir Molin

      Can somebody give me a tutorial link how to incerase my php memory limit?

  • http://howto.blbosti.com 5ulo

    I got this class working on our CMS. Works great (thanks for that), but each time I refresh webpage with resized image is the image re-sized and re-saved again. If there will be 100 people on the website and each one hits F5, what would happen? Is there some way to check existing resized image (width, height.. etc) and prevent resaving if the image options are the same? I’m php beginner so please be nice to me :))))
    Thank

    • http://sharedcorner.com Ianemv

      I thought the same thing . I believe the images should be cached after being rendered.

    • http://www.stinformatik.eu Johannes

      I think you should resize the image on upload and then just reference them in your view!

  • niki

    that was awesome! Tnx so much :)))

  • Nagaraju

    that was awesome!

  • http://- sgio

    thank you for gret tutorials. It is easy to understand.
    thx ^^

    I am a foreigner.

  • http://videoconferenciagvo.com Juan

    Thanks, very much, is usefull the class.

  • http://LoLbox.pl baambaam

    “Warning: imagesx(): supplied argument is not a valid Image resource in /home/(…)/resize.php on line 34″

    I have this warning and more but all are show by bad resource verification of images. Anybody have any solution for this?

  • http://aravindisonline.blogspot.com Aravind

    I love you man…. best script i ever found..

  • aashipathan

    Hi,
    Thanks for sharing this tutorial very nice

  • Maroun

    this is really the best image resizer on the fly php script I have ever used thanks you a lot!!!

  • Denis

    Hi there are problem if upload a image with a form
    whit this code:
    if($_FILES['img']['name'] != “”){

    // *** 1) Initialise / load image
    $resizeObj = new resize($_FILES['img']['tmp_name']);

    // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
    $resizeObj -> resizeImage(200, 200, ‘crop’);

    // *** 3) Save image
    $resizeObj -> saveImage($_FILES['img']['name'], 100);
    }

    there are problems:

    Warning: imagesx(): supplied argument is not a valid Image resource

    can anyone have got same problem?

    • Denis

      I dont know if other user risolved this problem, but after reading tutorials carefully, there is a problem.
      A class required a recource then before upload a file, verify if exist and then resize the image.

    • Ektoer

      The problem is:
      $resizeObj = new resize($_FILES['img']['tmp_name']); if you (by any means) print the ‘tmp_name’ of your file, you’ll get something like this: php/kodsaoov.dat or something, this is just a temporary placeholder for the file on the server, and of course, is not a valid image. this class(which by the way works perfectly for me) uses a string with the path of the image you’r using, given that it has been uploaded earlier on your server.

      Look for a solution to upload the image before resizing it, get the path and correct filename and then resize it…

      Hope this helps…

      Thanks

      • Karl von Karton

        Correct.

        Something like this:

        if(move_uploaded_file($_FILES['userfile']['tmp_name'], $yourPath.$yourImgName)){
        /* do the resizing here*/
        }

      • gus

        Thank you very much for your post, this helped me a lot

  • http://od3n.net/ od3n

    thanks for the tutorial! was looking for this!

  • Larry

    Can someone tell me how to use this with a form?

  • Neha

    But it is not working fine for PNG,Image is getting resized but not transparent.
    Kindly help me,what to do to resolve it??

  • dlnco

    Hi guys,

    Great class. But it isnt working for parts of my images. If i set this up on a local machine everything works great, but if i upload it to my server only the first feed of images are processed and the other two feeds of images give me back several error for each image (see below). Imagepath are stored in my database and grabbed by the script using a while loop. I also tried to set allow_url_fopen to on, but this doesnt seem to help.

    The odd thing is that its processing parts of all the images, but trowing errors at me on others.

    Could somebody support me with this?

    the errors i get:

    Warning: getimagesize() [function.getimagesize]: URL file-access is disabled in the server configuration in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 42

    Warning: getimagesize(http://static.fonq.nl/data/producten/19863-groot.jpg) [function.getimagesize]: failed to open stream: no suitable wrapper could be found in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 42

    Warning: imagesx(): supplied argument is not a valid Image resource in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 34

    Warning: imagesy(): supplied argument is not a valid Image resource in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 35

    Warning: Division by zero in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 119

    Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 65

    Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 66

    Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 206

    Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/admin/domains/domain.com/public_html/themes/feeds/resize-class.php on line 235

  • mhmd

    thanks a lot for that great job

    but the class saved the image as a black background !!!!

  • James

    Hello,

    First of all, great script!

    Secondly, I’d like to ask for some help. I’m creating thumbnail pictures using this script in a foreach loop.
    Now it should loop 10 times, because the array has 10 values.. (The loop works perfekty without the script.)

    The first 6 pictures are created successfully, but after that it seems the script has stopped.
    And doesn’t through any errors..

    Thanks for help!

  • Ryan Jansen

    Hi everyone, thanks for the tuts
    I’ve problem here, why I can’t resize picture with width/height over 3000px?

  • nicky

    This is a good, clear tutorial overall BUT, there is a major design problem!

    If you want to do a good OO programming, you have to be extremely careful on how you name you classes, methods and everything else!
    Avoid, as much as you can, making a class out of an action. The action has to be an internal method (in most cases) of the object.

    You can clearly see the problem here with the methods: resizeImage and saveImage, which are applied to an object of type … resize ?! It’s really confusing to my mind. I don’t know if you see where I’m getting to but well, let me tell you how I would have named them things myself!

    My stream of thoughts would be as follows: I am willing to make images resizable, okay, then I should have two choices doing it with PHP, whether making a plain old script which calls functions in a row and does the job at the end of the last line of code, or, do it with an Object Oriented approach (which is our interest here) and consider the fact that the action needed and “resizing”, okay, but resizing what? images! Alright, then I may create a class named “Image” which contains a public method called “resize”, and “save”, and “whatever you want to add as an internal functionality applied to the image object”.

    That’s all folks.

  • somnath Shinde

    Thanks for nice class..

    and it work fine as well resize image as per set size..

    And that class is easy to use as compares to other classes……….

    Thanks Again…

  • Gabriel

    Thanks you very much! very helpful.

  • Julius

    Thank you a lot, very simple and useful!!!

  • http://www.johnnyzone.com JDub

    You can easily make this function allow for resizing of transparent background PNG images. For the resizeImage() function, use this code, instead of what is in there by default:

    public function resizeImage($newWidth, $newHeight, $option=”auto”)
    {
    // *** Get optimal width and height – based on $option
    $optionArray = $this->getDimensions($newWidth, $newHeight, $option);

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

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

    // *** EDIT BY JDUB – add transparent background, for png images
    //2. Create an alpha-transparent color and fill the image with it */
    imagealphablending($this->imageResized, false);
    imagesavealpha($this->imageResized, true);
    $bg = imagecolorallocatealpha($this->imageResized, 0, 0, 0, 127);
    imagefilledrectangle($this->imageResized, 0, 0, $optimalWidth, $optimalHeight, $bg);
    imagecolortransparent($this->imageResized, $bg);
    // *** END EDIT BY JDUB

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

  • KAREEM

    Thanks a lot! this class saved me!

    but I faced a problem, when i recall this class more then one time from a loop it stucks!

    may you help me please.

  • Duy Mão

    Very good code. thanks so much

  • Sreeraj

    Thanks for the code.
    But am facing a problem.My code works perfectly on localhost. But when working with live server, all the images are cropped and saved turns to a black colored image.Could anyone get me a solution for this.

    Thanks in advance.

    • Iqbal

      Give 777 permission to the directly in which you are uploading resized pictures

  • Jamie

    Great little piece, used it to remedy a hole in a client side resizer and it ‘plugged and played’ very nicely. Thanks!

  • Eoghan

    This might be too late now, but is there a simple way of making the saved image an interlaced one?

  • knowlton

    when a photo is submitted from a phone camera in portrait mode, the resized image is rotated 90 degrees. Any idea why? Thanks

    • Muhammad Yahya Muhaimin

      it is because photos from most of digital cameras is actually landscape,
      the image is merely displayed as portrait,
      make sure you get information about the true value of its width and height.

  • http://vijaykumar.me vijay

    Thanks it worked. Thanks tutplus you are really awesome

  • Mushr00m

    I just tried this script, very nice thanks ! But if you use a smaller image than the desired width and height (with crop) it zoom and didn’t crop it. You can try by asking 120*170 and Crop with an image 80*300. It’s a big problem for because it should keep it without zomming, fill the back with color and crop the to big part. How can I do that ?

  • Tornike

    Very very nice image re-size script, huge thanks

  • name

    does any know why double the mysql records when trying to insert data that is added into loop “for” where the uploaded images are counted and

  • Adnan

    I tried to upload but not working. here is my code:

    error_reporting( E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING );

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

    $filename = $_FILES['image']['name'];
    $source = $_FILES['image']['tmp_name'];

    $target = ‘image/’.$filename;

    /******************************************************/
    if(move_uploaded_file($source, $target)){

    // *** 1) Initialise / load image
    $resizeObj = new resize($source);

    // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
    $resizeObj -> resizeImage(200, 200, ‘crop’);

    // *** 3) Save image
    $resizeObj -> saveImage($target,100);
    }

    ?>

    Can you solve this problem for me?

  • http://javiermejias.com Javier

    Thank you!!

    But I have a error when I use 1000 or more as width of new photo. What happen?

  • Yvo

    I do not understand this. How do I use it to resize multiple images and Upload by CMS? Besides, I can not use the index.php file, because that is the CMS. Please help me.

  • Ted

    How would I modify this for Codeigniter? I’ve got the resize class in a library and then I’m trying to initialize the object in another controller like this:

    function resizeTest(){

    $this->load->library(‘resize’);

    // *** 1) Initialize / load image
    $resizeObj = new $this->resize(‘sample.jpg’);

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

    // *** 3) Save image
    $resizeObj -> $this->resize->saveImage(‘sample-resized.gif’, 100);
    }

    I’m getting an error saying:

    Message: Missing argument 1 for resize::__construct(), called in /Applications/MAMP/htdocs/www/resources/labs/system/core/Loader.php on line 1099 and defined

    The problem seems to be that the argument is not getting passed to the constructor in the resize library but I’m not sure why.

    • http://twitter.com/scrivs Scrivs

      Ted You just have to pass the initial file when you load the library:


      $this->load->library('ImageResize', array('file' => $file));

      Then just call the functions as needed:

      $this->imageresize->resizeImage(400, 400, 'auto');

      $this->imageresize->saveImage('./temp/thumb_'.$file_name, 80);

  • http://www.acilkod.com/ Bunyamin

    Hello,

    I would like to know if I can use your source code in my application which I am planning to sell.

  • Jeremy

    The lack of security in this script is scary. It’s a nice starter script but DO NOT go off the supposed file extension to resize the image. You will be easily hacked if you use this on a live server. For personal use this is a great starter script!

  • Steph

    Hi,

    Your class is just wonderfull and very helpfull.

    Thank you :)

  • Tornike

    This is the best image re-size script I’ve ever seen. really. Huge thanks for sharing

  • caztillo

    Thank you, its a very nice class :D

  • http://www.facebook.com/dewan159 Ahmed Zain

    Great, I am using this code now and it works just fine.
    I have added these lines of code to save transparent PNG images:

    $black = imagecolorallocate($this->imageResized, 0, 0, 0);
    imagecolortransparent($this->imageResized, $black);
    imagepng($this->imageResized, $savePath, $invertScaleQuality);

    This seems to ruin the image; leaves a surrounding black line. Any solution?

    Thanks Again.

  • Marta

    Very smart, clean and efficient solution. Thanks to you, Jarrod Oberto, my hardship with resizing images had been overcome. Thank you very much. God bless you!

  • http://www.facebook.com/utshab.bhetuwal Utshab Bhetuwal

    Awesome , but i am having problem witht the image i upload from my own form .. Can you please explain how uploaded files can be used to resize the image ???

  • rmj

    probably the best and “simplest” opportunity for this issue, great!

  • Potheek

    Incredibly easy to understand tutorial :)

    I really liked the way you have proceeded :)

    Keep it up :D

  • Shahzad Ahmed

    I am using this code and it made my life easier. i love the crop which is perfect.

    1 question if some one upload big image then its fine but when some one upload small pic so crop function still work and make that small image to final size and picture distort .

    how can i tell script not to run when image is small then final size.

    eg
    Final size is 200 x 150

    so if some one upload image of 150 x 100 i dont want script to run and to make this small image of 200 x 150