How To 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 it 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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

 

DOWNLOAD & NOTES

First, here is the download link to the source code as promised.

 

QUICK NOTES

  • Please make sure that the GD extension is enabled in the php.ini file – extension=gd (or gd2 prior to PHP8).
  • 1-basic-resize.php is a basic example of resizing JPG images.
  • 2-transparent-resize.php resizing of transparent PNG images.
  • 3-resizer.php is an image resize function that you can use in your own project.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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 = imagecreatefromjpeg("Acate.jpg"); // original 600 x 324 px

// (B) EMPTY CANVAS WITH REQUIRED DIMENSIONS
// IMAGECREATETRUECOLOR(WIDTH, HEIGHT)
$resized = imagecreatetruecolor(300, 162); // 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, 162, 600, 324);

// (D) SAVE/OUTPUT RESIZED IMAGE
imagejpeg($resized, "resized.jpg");

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

This is an actual working version of the introduction above, 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("Bdoge.png"); // original 450 x 600 px

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

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

// (D) RESIZE THE IMAGE
imagecopyresampled($resized, $original, 0, 0, 0, 0, 225, 300, 450, 600);

// (E) SAVE/OUTPUT RESIZED IMAGE
imagepng($resized, "resized.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) FILE CHECKS
  // (A1) ALLOWED IMAGE FILE EXTENSIONS
  $ext = strtolower(pathinfo($source)["extension"]);
  if (!in_array($ext, ["bmp", "gif", "jpg", "jpeg", "png", "webp"])) {
    throw new Exception("Invalid image file type");
  }
 
  // (A2) SOURCE IMAGE NOT FOUND!
  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" . ($ext=="jpg" ? "jpeg" : $ext);
  $fnOutput = "image" . ($ext=="jpg" ? "jpeg" : $ext);

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

  // (C3) TRANSPARENT IMAGES ONLY
  if ($ext=="png" || $ext=="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("Acate.jpg", "resized-A.jpg", 50);
resizer("Bdoge.png", "resized-B.png", 25);

// (E2) FIXED DIMENSION RESIZE + QUALITY
resizer("Acate.jpg", "resized-AA.jpg", [200, 400], 20);
resizer("Bdoge.png", "resized-BB.png", [300, 250], 1);

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.

 

 

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 “How To 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 *