Resize Images in PHP (With 4 Lines Of Code!)

Welcome to a tutorial on how to resize images in PHP. So you have a project that deals with images, and want to resize them due to space restrictions… or maybe you just want to create thumbnails of the uploaded images.

An easy way to resize images in PHP is to use the GD library:

  • $original = imagecreatefromjpeg("ORIGINAL.jpg");
  • $resized = imagecreatetruecolor(NEW WIDTH, NEW HEIGHT);
  • imagecopyresampled($resized, $original, 0, 0, 0, 0, NEW WIDTH, NEW HEIGHT, WIDTH, HEIGHT);
  • imagejpeg($resized, "RESIZED.jpg");

That covers the basics, but how do we resize transparent images? Let us walk through with a few more examples – Read on!

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

PHP IMAGE RESIZE

All right, let us now get into the examples of how to resize images in PHP.

 

1) SIMPLE IMAGE RESIZE

1-basic-resize.php
<?php
// (A) READ THE ORIGINAL IMAGE
$original = imagecreatefrompng("PHP-resize-a.png"); // original 600 x 400 px

// (B) EMPTY CANVAS WITH REQUIRED DIMENSIONS
// IMAGECREATETRUECOLOR(WIDTH, HEIGHT)
$resized = imagecreatetruecolor(300, 200); // smaller by 50%

// (C) RESIZE THE IMAGE
// IMAGECOPYRESAMPLED(TARGET, SOURCE, TX, TY, SX, SY, TWIDTH, THEIGHT, SWIDTH, SHEIGHT)
imagecopyresampled($resized, $original, 0, 0, 0, 0, 300, 200, 600, 400);

// (D) SAVE/OUTPUT RESIZED IMAGE
imagepng($resized, "demoA.png");

// (E) OPTIONAL - CLEAN UP
imagedestroy($original);
imagedestroy($resized);

This is an actual working version of the introduction above, which should be very straightforward and easy. To resize an image – We only need to create an empty canvas, then copy and resize the source image over.

 

 

2) RESIZING TRANSPARENT IMAGES

2-transparent-resize.php
<?php
// (A) READ THE ORIGINAL IMAGE
$original = imagecreatefrompng("PHP-resize-b.png"); // original 512 x 512 px

// (B) EMPTY CANVAS WITH REQUIRED DIMENSIONS
$resized = imagecreatetruecolor(256, 256); // smaller by 50%

// (C) PREFILL WITH TRANSPARENT LAYER
imagealphablending($resized, false);
imagesavealpha($resized, true);
imagefilledrectangle(
  $resized, 0, 0, 256, 256, 
  imagecolorallocatealpha($resized, 255, 255, 255, 127)
);

// (D) RESIZE THE IMAGE
imagecopyresampled($resized, $original, 0, 0, 0, 0, 256, 256, 512, 512);

// (E) SAVE/OUTPUT RESIZED IMAGE
imagepng($resized, "demoB.png");

// (F) OPTIONAL - CLEAN UP
imagedestroy($original);
imagedestroy($resized);

Yep, pretty much the same. We only added an extra section (C) – Set the $resized canvas to alpha (transparent), and fill it with a transparent layer before resizing.

 

 

3) RESIZE IMAGE FUNCTION

3-resizer.php
<?php
function resizer ($source, $destination, $size, $quality=null) {
// $source - Original image file
// $destination - Resized image file name
// $size - Single number for percentage resize
// Array of 2 numbers for fixed width + height
// $quality - Optional image quality. JPG & WEBP = 0 to 100, PNG = -1 to 9
 
  // (A) CHECKS
  $allowed = ["bmp", "gif", "jpg", "jpeg", "png", "webp"];
  $sExt = strtolower(pathinfo($source)["extension"]);
  $dExt = strtolower(pathinfo($destination)["extension"]);
  if (!in_array($sExt, $allowed)) { throw new Exception("$sExt - Invalid image file type"); }
  if (!in_array($dExt, $allowed)) { throw new Exception("$dExt - Invalid image file type"); }
  if (!file_exists($source)) { throw new Exception("Source image file not found"); }

  // (B) IMAGE DIMENSIONS
  $dimensions = getimagesize($source);
  $width = $dimensions[0];
  $height = $dimensions[1];
  if (is_array($size)) {
    $new_width = $size[0];
    $new_height = $size[1];
  } else {
    $new_width = ceil(($size/100) * $width);
    $new_height = ceil(($size/100) * $height);
  }

  // (C) RESIZE
  // (C1) RESPECTIVE PHP IMAGE FUNCTIONS
  $fnCreate = "imagecreatefrom" . ($sExt=="jpg" ? "jpeg" : $sExt);
  $fnOutput = "image" . ($dExt=="jpg" ? "jpeg" : $dExt);

  // (C2) IMAGE OBJECTS
  $original = $fnCreate($source);
  $resized = imagecreatetruecolor($new_width, $new_height); 

  // (C3) TRANSPARENT IMAGES ONLY
  if ($sExt=="png" || $sExt=="gif") {
    imagealphablending($resized, false);
    imagesavealpha($resized, true);
    imagefilledrectangle(
      $resized, 0, 0, $new_width, $new_height,
      imagecolorallocatealpha($resized, 255, 255, 255, 127)
    );
  }

  // (C4) COPY & RESIZE
  imagecopyresampled(
    $resized, $original, 0, 0, 0, 0, 
    $new_width, $new_height, $width, $height
  );

  // (D) OUTPUT & CLEAN UP
  if (is_numeric($quality)) {
    $fnOutput($resized, $destination, $quality);
  } else {
    $fnOutput($resized, $destination);
  }
  imagedestroy($original);
  imagedestroy($resized);
}

// (E) EXAMPLE USAGE
// (E1) PERCENTAGE RESIZE
resizer("PHP-resize-a.png", "demoC.jpg", 50);
resizer("PHP-resize-b.png", "demoD.png", 25);

// (E2) FIXED DIMENSION RESIZE + QUALITY
resizer("PHP-resize-a.png", "demoE.jpg", [150, 100], 60);
resizer("PHP-resize-b.png", "demoF.webp", [128, 128], 70);

Finally, this function is kind of a small convenience for you guys to use in your own projects – Basically, a “smart version” of the above examples that do checks and auto-dimension calculations. Not the best in the world, but should be good enough for a kickstart.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.

Buy Me A Meal Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

EXTRA BITS & LINKS

We are now done with the scripts, here are some small extras and links that may be useful to you.

 

SUMMARY OF FUNCTIONS

Function Description PHP Manual
imagecreatefromjpeg(FILE) The whole family of imagecreatefromXXX() functions are used to create an image object from the specified file. Click Here
imagecreatetruecolor(WIDTH, HEIGHT) Create an empty canvas with a specified width and height. Click Here
imagesavealpha(IMAGE, BOOL) Set the image to retain the alpha channel (transparency). Click Here
imagecopyresampled(DESTINATION, SOURCE, DX, DY, SX, SY) Copy and resize. Click Here
imagejpeg(IMAGE, FILE NAME) The whole family of imageXXX() is used to save and output an image object. Click Here
imagedestroy(IMAGE) Destroy an image. Click Here

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Resize Images In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope it has solved your image resize problems, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

13 thoughts on “Resize Images in PHP (With 4 Lines Of Code!)”

  1. Thanks for this. One thing to note is the output ignores orientation in the exif data of the source image. The code below will fix that.

    // Correct image orientation
    $exif = exif_read_data($source);
    if ($exif && isset($exif['Orientation'])) {
      $orientation = $exif['Orientation'];
      switch ($orientation) {
        case 1:
          // no rotation necessary
          break;
    
        case 3: 
          $resized = imagerotate($resized,180,0);
          break;
                                   
        case 6: 
          $resized = imagerotate($resized,270,0);
          break;
                       
        case 8: 
          $resized = imagerotate($resized,90,0);	
          break;
      }
    }
  2. Hello W.S. TOH,
    Thank you very much for the tutorial, I was looking for something like this and your code explained very well and cleanly how to make php image functions properly work. It sparked my mind hehe. Thanks again!

  3. Sure looks like a cool & helpful php code
    but why you could not add a Page where user can Upload Image and your script does in the same process the resizing of the image… with a working example page…
    It would be for you… 5 min of extra effort
    – While I’m scratching my head for hours 🙂

      1. Do you have any example of how this would implement well? I customized the $fn variables accordingly, but may be missing sth as the png still come out in black.

  4. Interesting post. Was surprised that PHP had a bunch of functions to deal with images, compression, resizing etc.

Leave a Comment

Your email address will not be published. Required fields are marked *