How to Resize Images in PHP

August 2020 | John Binzak
Learn how to resize and rescale images in PHP.

Overview

With web apps, we commonly have users upload photos. However when the time comes to display those images, we don't always need the original size & resolution. Big images have big load times and can cause apps to slow down. The common solution is to resize and save multiple resolutions of the same file. Here we will show you how to resize an image with .

Reusable Resize Function

Let's first create a simple php file called for demo purposes. Then let's create a function called which intakes 2 arguments. The first being a string . The second being an optional int . This will be our reusable resize function. It will return an image resource upon success, or the false boolean if an error occurs.


    /**
    * @param $image_url
    * @param int $max_dimension
    * @return bool|resource
    */
    function createResizedImage($image_url, $max_dimension = 200) 

Rescale Dimensions

The next thing we want to do is find the new dimensions of our resized image. We will have to make sure the new dimensions have the same ratio as the original image otherwise the output will look distorted. So in our function all we do is get the original dimensions (width & height), then find the biggest of those 2, set the largest to the new max dimension and scale the other appropriately.


    // get the dimensions
    list($width, $height) = getimagesize($image_url);

    // if no dimension, exit
    if(empty($width) || empty($height)){
        return false;
    }

    // rescale dimensions
    if ($width > $height) {
        $new_width = $max_dimension;
        $new_height = $max_dimension * ($height/$width);
    } else {
        $new_height = $max_dimension;
        $new_width = $max_dimension * ($width/$height);
    }

    

Create Image Resource from URL

Next in our function we need to create an image resource from the original image url. Depending on what image types you expect to use, you might need to modify this function to support them. For now, we aim to support and . We first attempt to get the file extension from the url. Then based on the extension, we either call or . It is best to wrap these calls in a block to prevent your script from crashing. If you are performing batch resizing, error handling will be key.


    // get type based on extension
    $path_parts = pathinfo($image_url);
    if(!isset($path_parts['extension'])){
        return false;
    }

    try{
        // create image
        if(strtoupper($path_parts['extension']) === 'JPEG' || strtoupper($path_parts['extension']) === 'JPG'){
            $src = imagecreatefromjpeg($image_url);
        }else{
            $src = imagecreatefrompng($image_url);
        }
    }catch (\Exception $e){
        try{
            // try one more time
            $src = imagecreatefromjpeg($image_url);
        }catch (\Exception $e){
            return false;
        }
    }
    

New Resized Resource

Then final step in our function is to create and return the resized image resource.


    // new resized resource
    $dst = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $dst;
    

How to Call Function

Now that we have our resize function we can easily resize an image from an image url and save it into a temp or final location.


// our image url
$original_image_url = "https://images.pexels.com/photos/861321/pexels-photo-861321.jpeg";

// new image
$resized_image = createResizedImage($original_image_url);
if($resized_image !== false){

    // save in temp location
    $file_path = tempnam("/tmp", time() ."_OUR_RESIZED_IMG");
    imagepng($resized_image, $file_path);
}

Summary

Now you can easily resize images no problem. Perhaps now you will resize user profile pictures to thumbnails. I would recommend that you create an async task or cronjob to resize batch images, opposed to in-sync with upload. You can find the source code here.