# Image Resizing Made Easy With PHP

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 and expandable.

## Introduction

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

• easy to use
• format independent: can open, resize, and save a number of different image formats
• intelligent sizing: no image distortion!
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.

## 1. Preparation

The first step is easy. In your working directory, create two files: one called index.php and the other resize-class.php

## 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, and we set the dimensions we want to resize the image to and the type of resizing. Then we save the image, choosing the image format and quality we want. Save and close your index.php file.

 1 // *** Include the class  2 include("resize-class.php");  3 4 // *** 1) Initialize / load image  5 $resizeObj = new resize('sample.jpg');  6 7 // *** 2) Resize image (options: exact, height, width, auto, crop)  8 $resizeObj -> resizeImage(150, 100, 'crop');  9 10 // *** 3) Save image  11 $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. ## 3. Create the 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 2. Once our pattern has been created, we create instances of this pattern, called objects. 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 where 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, and 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.  1  Class resize  2  {  3  // *** Class variables  4 5  public function __construct()  6  {  7 8  }  9  }  That's a double underscore for the construct method. ## 4. Code the Constructor Now 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 the implementation of this method 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 limiting 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.

 1  Class resize  2  {  3  // *** Class variables  4  private $image;  5  private$width;  6  private $height;  7 8  function __construct($fileName)  9  {  10  // *** Open up the file  11  $this->image =$this->openImage($fileName);  12 13  // *** Get width and height  14 $this->width = imagesx($this->image);  15 $this->height = imagesy($this->image);  16  }  17  }  The imagesx() and imagesy() methods are built-in functions that are part of the GD library. They retrieve the width and height of your image, respectively. ## 5. Opening the Image In the previous step, we called the custom method openImage(). In this step, we're going to implement the functionality inside 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 which GD Library function it calls to open the image. This is easily achieved by comparing the file's extension with a switch statement. We extract the extension from the filename by using the strrchr() function in PHP, which returns part of the main string from the last occurrence of the specified character till its end. For example, the filename papaya.jpg will give us .jpg, and the filename i.like.papaya.jpg will also give us .jpg. After determining the extension, we use the appropriate imagecreatefrom function to get back an image resource.  1 private function openImage($file)  2 {  3  // *** Get extension  4  $extension = strtolower(strrchr($file, '.'));  5 6  switch($extension)  7  {  8  case '.jpg':  9  case '.jpeg':  10 $img = @imagecreatefromjpeg($file);  11  break;  12  case '.gif':  13 $img = @imagecreatefromgif($file);  14  break;  15  case '.png':  16 $img = @imagecreatefrompng($file);  17  break;  18  default:  19 $img = false;  20  break;  21  }  22  return $img;  23 }  ## 6. How to Resize 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. (width) 3. Resize by height—like resize by width, but the height will be set and width adjusted dynamically. (height) 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 favorite. Exact size, no distortion. (crop) ## 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 by reference—but I'm not a huge fan of that. The second part is what performs the actual resizing. We will be using two built-in PHP functions for our resizing. They are: • imagecreatetruecolor • imagecopyresampled I recommend that you read about them in the documentation. In short, the imagecreatetruecolor() function will return an image object that represents a black image of a specified size. The imagecopyresampled() function is used to copy and resize part of an image with resampling. 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.

 1 // *** Add to class variables  2 private $imageResized;  3 4 public function resizeImage($newWidth, $newHeight,$option="auto")  5 {  6 7  // *** Get optimal width and height - based on $option  8 $optionArray = $this->getDimensions($newWidth, $newHeight, strtolower($option));  9 10  $optimalWidth =$optionArray['optimalWidth'];  11  $optimalHeight =$optionArray['optimalHeight'];  12 13  // *** Resample - create image canvas of x, y size  14  $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);  15  imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0,$optimalWidth, $optimalHeight,$this->width, $this->height);  16 17  // *** if option is 'crop', then crop too  18  if ($option == 'crop') {  19  $this->crop($optimalWidth, $optimalHeight,$newWidth, $newHeight);  20  }  21 }  In the above code snippet, we calculate the new image dimensions and create a true color image object accordingly. This image object is then passed to imagecopyresampled() where the data from the original image is copied over it. Which part is copied depends on the rest of the parameters. ## 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, which we'll be creating in the next step.  1 private function getDimensions($newWidth, $newHeight,$option)  2 {  3 4  switch ($option)  5  {  6  case 'exact':  7 $optimalWidth = $newWidth;  8 $optimalHeight= $newHeight;  9  break;  10  case 'height':  11 $optimalWidth = $this->getSizeByFixedHeight($newHeight);  12  $optimalHeight=$newHeight;  13  break;  14  case 'width':  15  $optimalWidth =$newWidth;  16  $optimalHeight=$this->getSizeByFixedWidth($newWidth);  17  break;  18  case 'auto':  19 $optionArray = $this->getSizeByAuto($newWidth, $newHeight);  20 $optimalWidth = $optionArray['optimalWidth'];  21 $optimalHeight = $optionArray['optimalHeight'];  22  break;  23  case 'crop':  24 $optionArray = $this->getOptimalCrop($newWidth, $newHeight);  25 $optimalWidth = $optionArray['optimalWidth'];  26 $optimalHeight = $optionArray['optimalHeight'];  27  break;  28  }  29  return array('optimalWidth' =>$optimalWidth, 'optimalHeight' => $optimalHeight);  30 }  At this point, we are simply calling different helper methods that we will implement in the next section. ## 9. Optimal Dimensions When the resizing option is set to height or width, we use the aspect ratio of the original image to calculate the appropriate width and height for our new image.  1 private function getSizeByFixedHeight($newHeight)  2 {  3  $ratio =$this->width / $this->height;  4 $newWidth = $newHeight *$ratio;  5  return $newWidth;  6 }  7 8 private function getSizeByFixedWidth($newWidth)  9 {  10  $ratio =$this->height / $this->width;  11 $newHeight = $newWidth *$ratio;  12  return $newHeight;  13 }  When the resizing option is set to auto, we use the original width and height of the image to determine whether the resized image should have a fixed width or height. For images in landscape orientation, we keep the width fixed. For images in portrait orientation, we keep the height fixed. If the original image is a square, we pick the fixed dimension using the new width and height value.  1 private function getSizeByAuto($newWidth, $newHeight)  2 {  3  if ($this->height < $this->width)  4  // *** Image to be resized is wider (landscape)  5  {  6 $optimalWidth = $newWidth;  7 $optimalHeight= $this->getSizeByFixedWidth($newWidth);  8  }  9  elseif ($this->height >$this->width)  10  // *** Image to be resized is taller (portrait)  11  {  12  $optimalWidth =$this->getSizeByFixedHeight($newHeight);  13 $optimalHeight= $newHeight;  14  }  15  else  16  // *** Image to be resized is a square  17  {  18  if ($newHeight < $newWidth) {  19 $optimalWidth = $newWidth;  20 $optimalHeight= $this->getSizeByFixedWidth($newWidth);  21  } else if ($newHeight >$newWidth) {  22  $optimalWidth =$this->getSizeByFixedHeight($newHeight);  23 $optimalHeight= $newHeight;  24  } else {  25  // *** Square being resized to a square  26 $optimalWidth = $newWidth;  27 $optimalHeight= $newHeight;  28  }  29  }  30 31  return array('optimalWidth' =>$optimalWidth, 'optimalHeight' => $optimalHeight);  32 }  33 34 private function getOptimalCrop($newWidth, $newHeight)  35 {  36 37 $heightRatio = $this->height /$newHeight;  38  $widthRatio =$this->width / $newWidth;  39 40  if ($heightRatio < $widthRatio) {  41 $optimalRatio = $heightRatio;  42  } else {  43 $optimalRatio = $widthRatio;  44  }  45 46 $optimalHeight = $this->height /$optimalRatio;  47  $optimalWidth =$this->width / $optimalRatio;  48 49  return array('optimalWidth' =>$optimalWidth, 'optimalHeight' => $optimalHeight);  50 }  The getOptimalCrop() method might seem a bit confusing at first because we are still calculating $optimalHeight and $optimalWidth, which we use for resizing. The reason is that instead of cropping the image directly to the specified width and height, our class crops the images after resizing. Let's say the dimensions of an image are 1920w and 1080h, and you want to crop it to 1200w and 200h. As you can see, the ratio of the original width to the new width will be lower than the corresponding height ratio. Therefore, the image will first need to be resized in such a way that its width comes down to 1200 and the height changes accordingly. The actual cropping of the image will be done after the resizing is complete. ## 10. Crop If you opted 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.  1 private function crop($optimalWidth, $optimalHeight,$newWidth, $newHeight)  2 {  3  // *** Find center - this will be used for the crop  4 $cropStartX = ( $optimalWidth / 2) - ($newWidth /2 );  5  $cropStartY = ($optimalHeight/ 2) - ( $newHeight/2 );  6 7 $crop = $this->imageResized;  8  //imagedestroy($this->imageResized);  9 10  // *** Now crop from center to exact requested size  11  $this->imageResized = imagecreatetruecolor($newWidth , $newHeight);  12  imagecopyresampled($this->imageResized, $crop , 0, 0,$cropStartX, $cropStartY,$newWidth, $newHeight ,$newWidth, $newHeight);  13 }  ## 11. Save the Image We're getting there; almost done. It's now time to save the image. We pass in the path and specify the image quality we would like ranging from 0-100, 100 being the best. Then we 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. PNGs 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. So we can do a bit of magic to standardize everything.  1 public function saveImage($savePath, $imageQuality="100")  2 {  3  // *** Get extension  4 $extension = strrchr($savePath, '.');  5 $extension = strtolower($extension);  6 7  switch($extension)  8  {  9  case '.jpg':  10  case '.jpeg':  11  if (imagetypes() & IMG_JPG) {  12  imagejpeg($this->imageResized,$savePath, $imageQuality);  13  }  14  break;  15 16  case '.gif':  17  if (imagetypes() & IMG_GIF) {  18  imagegif($this->imageResized, $savePath);  19  }  20  break;  21 22  case '.png':  23  // *** Scale quality from 0-100 to 0-9  24 $scaleQuality = round(($imageQuality/100) * 9);  25 26  // *** Invert quality setting as 0 is best, not 9  27 $invertScaleQuality = 9 - $scaleQuality;  28 29  if (imagetypes() & IMG_PNG) {  30  imagepng($this->imageResized, $savePath,$invertScaleQuality);  31  }  32  break;  33 34  // ... etc  35 36  default:  37  // *** No extension - No save.  38  break;  39  }  40 41  imagedestroy(\$this->imageResized);  42 } 

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, and I hope you find it useful.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries.