PHPDeveloper

Image Resizing Made Easy with PHP

by Jarrod posted 3 years ago
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 - reusuable pieces of functionality that we call to do the dirty work. Let's take a look at creating our own class for just this task.

Note: The article was originally published on net tuts+ on March 18th, 2010.

Tutorial Details

  • Program: PHP 5+
  • Version: 1.0
  • Requirments: GD Library
  • Difficulty: Intermediate
  • Estimated Completion Time: 40min

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 just what we're trying to achieve, we'll begin by coding the calls we'll use to resize your image. 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) Initialise / 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. It's all about flexability.

Step 3 - Class skeleton

It's Object-Oriented Programming (OOP) that makes this sense of ease possible. By creating a class, 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 rewite any of the resizing code - you only need to call the appropriate methods just like we did in step 2. Once our pattern is created we create instances of this pattern called objects.

We're going to 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 initialising - 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're going to 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, lets 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 get 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 - Resizing. But how?

This is were 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 do perform our resize; so it makes sense to pass in the width and height as well as information as to how we want to resize our 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. So not an exact height or width, but still close. 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 the 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!

Here is the resize method. There's really just two parts here. 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 imagecreatetruecolor imagecopyresampled.

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 - Creating options

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

Few. We're getting there. Almost done. 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, by that I mean calculating, to standardise 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.

Final Words

Well that's it, folks. Thank you for following this tutorial, I hope you find it useful. I appreciate any feedback in the comments below.

Comments for Image Resizing Made Easy with PHP

  • Donald Duck
    Igor 2012-06-21 01:04:08

    Hello thanks for script. But it's not working with big images: above 2M. Max allowed file size is 8 mb.

  • Donald Duck
    Gururaj 2012-11-23 05:03:35

    Hi Jarrod, Hope you are doing good. I had found an issue with resizing PNG images, resized PNG will have the black background. I have fixed this issue, could you please confirm your email address to send update resizing the class through email. Thank you. Best Regards, Gururaj

  • Donald Duck
    Jason 2013-07-13 04:30:02

    Hey Jarrod, I have been using your class for a bit now, but still not able to get BMP file uploaded. Does this class take in to account this file type ?

  • Donald Duck
    Lester Fibla Saavedra 2013-12-22 19:17:41

    Hi. Do you have a github profile? is the resize class public in github? I'm using that class in a couple of projects and i made some changes (a little upgrade) for choose corner or center like referer point for crop images. Would you like i send the code? PS: sorry for my english. i speak spanish.

  • Donald Duck
    Brave 2014-02-25 00:40:36

    Hi, I faced problem in png file. Black png file loaded. Please help me. What problem comes ? please send me mail in my email address . I like this class thanks :)

Type Your Comment