Resizing the Uploaded Image in PHP using GD extension Tutorial

In this tutorial, you will learn how to resize the image file before saving it into a directory using PHP and GD Library. This process is really useful when you are developing a web application using PHP Language which has some features that include uploading Image files such as system users avatar, image/gallery thumbnails, and etc.

PHP GD extension/library offers Graphics Drawing toos to manage image data such as cropping, compressing, filtering, and etc.

We will create a simple web application where the user can upload an image and the application itself will convert or resize the image to the specified height and width of the user. The application will be only accepting PNG, JPG, or JPEG files to upload. We will be using GD's imagecreatetruecolor(), imagecreatefrompng(), imagecreatefromjpeg(), imagecopyresampled(), and imagepng() functions in order to meet the simple application's requirement.

Getting Started

Kindly download and install a local web-server such as XAMPP/WAMP to run our PHP Script. Next, open your php.ini file and uncomment the Gd extention. To this, remove the semicolon before the extension. See th image below.

GD Extension

After that, open your XAMP/WAMP's Control Panel and start the Apache.

Also, download Bootstrap for the user interface.

Creating the Interface

We will be only making a simple user interface for this application which contains Form Panel where we can upload the image and specify the size we wanted for the convertion. Copy/Paste the script below and save the file as index.php. Make sure that path of external CSS and Script files are right according to your bootstrap assets located in your end.

  1. <?php
  2. session_start();
  3. ?>
  4. <!DOCTYPE html>
  5. <html lang="en">
  6.     <meta charset="UTF-8">
  7.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9.     <title>Image Resize in PHP</title>
  10.     <link rel="stylesheet" href="./Font-Awesome-master/css/all.min.css">
  11.     <link rel="stylesheet" href="./css/bootstrap.min.css">
  12.     <script src="./js/jquery-3.6.0.min.js"></script>
  13.     <script src="./js/bootstrap.min.js"></script>
  14.     <style>
  15.         :root{
  16.             --bs-success-rgb:71, 222, 152 !important;
  17.         }
  18.         html,body{
  19.             height:100%;
  20.             width:100%;
  21.         }
  22.         .display-img{
  23.             object-fit:scale-down;
  24.             object-position:center center;
  25.             height:35vh;
  26.         }
  27.     </style>
  28. </head>
  29.     <main>
  30.     <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
  31.         <div class="container">
  32.             <a class="navbar-brand" href="./">
  33.             Image Resize in PHP
  34.             </a>
  35.             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  36.             <span class="navbar-toggler-icon"></span>
  37.             </button>
  38.             <div class="collapse navbar-collapse" id="navbarNav">
  39.                 <ul class="navbar-nav">
  40.                     <li class="nav-item">
  41.                         <a class="nav-link <?php echo ($page == 'home')? 'active' : '' ?>" aria-current="page" href="./">Home</a>
  42.                     </li>
  43.                 </ul>
  44.             </div>
  45.         </div>
  46.     </nav>
  47.     <div class="container py-3" id="page-container">
  48.         <?php
  49.            if(isset($_SESSION['flashdata'])):
  50.        ?>
  51.         <div class="dynamic_alert alert alert-<?php echo $_SESSION['flashdata']['type'] ?>">
  52.         <div class="float-end"><a href="javascript:void(0)" class="text-dark text-decoration-none" onclick="$(this).closest('.dynamic_alert').hide('slow').remove()">x</a></div>
  53.             <?php echo $_SESSION['flashdata']['msg'] ?>
  54.         </div>
  55.         <?php
  56.            unset($_SESSION['flashdata']);
  57.            endif;
  58.        ?>
  59.         <h3 class="fw-bold">Image Resize in PHP using GD Library</h3>
  60.         <hr>
  61.         <small>This is a simple web-application that saving and resizing the size of uploaded image file.</small>
  62.  
  63.         <div class="col-12 row row-cols-2 gx-5 py-5">
  64.             <div class="col-md-4">
  65.                 <div class="card">
  66.                     <div class="card-body">
  67.                         <form action="upload_file.php" enctype="multipart/form-data" method="POST">
  68.                         <div class="form-group">
  69.                             <div class="mb-3">
  70.                                 <label for="formFile" class="form-label">Image to Upload</label>
  71.                                 <input class="form-control form-control-sm rounded-0" type="file" name="image" id="formFile" accept="image/png,image/jpeg" required>
  72.                             </div>
  73.                         </div>
  74.                         <div class="form-group">
  75.                             <label for="height" class="control-label">Height</label>
  76.                             <input type="number" name="height" id="height" value="50" class="form-control form-control-sm rounded-0 text-end" required>
  77.                         </div>
  78.                         <div class="form-group">
  79.                             <label for="width" class="control-label">Width</label>
  80.                             <input type="number" name="width" id="width" value="50" class="form-control form-control-sm rounded-0 text-end" required>
  81.                         </div>
  82.                         <div class="form-group d-flex justify-content-end my-3">
  83.                             <div class="col-auto">
  84.                                 <button class="btn btn-sm btn-primary rounded-0" type="submit">Upload</button>
  85.                                 <button class="btn btn-sm btn-dark rounded-0" type="reset">Reset</button>
  86.                             </div>
  87.                         </div>
  88.                         </form>
  89.                     </div>
  90.                 </div>
  91.                
  92.             </div>
  93.             <div class="col-md-8">
  94.                 <div class="card h-100">
  95.                     <div class="card-body h-100 d-flex justiy-content-center align-items-center">
  96.                         <?php
  97.                            $original_file = "./upload/original.png";
  98.                            $resized_file = "./upload/resized.png";
  99.                        ?>
  100.                         <?php if(!is_file($original_file) && !is_file($resized_file)): ?>
  101.                             <div class="text-center w-100 lh-1">
  102.                                 <h3 class="fw-bolder">Please Upload Image First</h3>
  103.                                 <center><hr style="width:30% !important;height:3px !important" class="bg-primary rounded-pill bg-opacity-100"/></center>
  104.                                 <span class="fs-6 fw-light">Image file will be displayed here.</span>
  105.                             </div>
  106.                         <?php else: ?>
  107.                             <?php
  108.                            list($o_img_width,$o_img_height) = getimagesize($original_file);
  109.                            list($r_img_width,$r_img_height) = getimagesize($resized_file);
  110.                            ?>
  111.                             <div class="w-100 row row-cols-2 gx-5 mx-0">
  112.                                 <div class="col-md-6">
  113.                                     <div class="card">
  114.                                         <img src="<?php echo $original_file."?".time() ?>" class='img-top display-img bg-dark' alt="Original Image File">
  115.                                         <div class="card-body">
  116.                                             <div class="rounded-pill px-3 bg-primary text-light fs-5 fw-bolder">Original</div>
  117.                                             <p class="lh-1 mt-2">
  118.                                                 <span class="fs-6">Width: </span>
  119.                                                 <span class="fs-5 fw-bold"><?php echo $o_img_width ?></span>
  120.                                                 <br>
  121.                                                 <span class="fs-6">Height: </span>
  122.                                                 <span class="fs-5 fw-bold"><?php echo $o_img_height ?></span>
  123.                                             </p>
  124.                                             <center><a class="btn btn-sm btn-primary rounded-pill px-4" href='<?php echo $original_file."?".time() ?>' target='_blank'>View</a></center>
  125.                                         </div>
  126.                                     </div>
  127.                                 </div>
  128.                                 <div class="col-md-6">
  129.                                     <div class="card">
  130.                                         <img src="<?php echo $resized_file."?".time() ?>" class='img-top display-img bg-dark' alt="Resized Image File">
  131.                                         <div class="card-body">
  132.                                             <div class="rounded-pill px-3 bg-success text-light fs-5 fw-bolder">Resized</div>
  133.                                             <p class="lh-1 mt-2">
  134.                                                 <span class="fs-6">Width: </span>
  135.                                                 <span class="fs-5 fw-bold"><?php echo $r_img_width ?></span>
  136.                                                 <br>
  137.                                                 <span class="fs-6">Height: </span>
  138.                                                 <span class="fs-5 fw-bold"><?php echo $r_img_height ?></span>
  139.                                             </p>
  140.                                             <center><a class="btn btn-sm btn-primary rounded-pill px-4" href='<?php echo $resized_file."?".time() ?>' target='_blank'>View</a></center>
  141.                                         </div>
  142.                                     </div>
  143.                                 </div>
  144.  
  145.                             </div>
  146.                         <?php endif; ?>
  147.                     </div>
  148.                 </div>
  149.             </div>
  150.         </div>
  151.     </div>
  152.     </main>
  153. </body>
  154. </html>

Creating the Main Function

The script shown below is the code process the user file uploaded file. In contains the checking of the validity of the file upload, directory and file creation, and the most important is the script for resizing the uploaded image. Save the script in a new PHP file as upload_filephp.

  1. <?php
  2. // creating the upload directory if doesn't exists
  3. if(!is_dir('./upload'))
  4. mkdir('./upload');
  5. // Extracting the POST Data into variables
  6. extract($_POST);
  7. if(isset($_FILES['image']) && !empty($_FILES['image'])){
  8.     //Image File Uploaded
  9.     $upload = $_FILES['image'];
  10.     // Identifing File Mime Type
  11.     $type = mime_content_type($upload['tmp_name']);
  12.     // Valid File types
  13.     $valid_type = array('image/png','image/jpeg');
  14.     if(!in_array($type,$valid_type)){
  15.         $_SESSION['flashdata']['type']="danger";
  16.         $_SESSION['flashdata']['msg']="Image File type is invalid.";
  17.     }else{
  18.         // new size variables
  19.         $new_height = $height; // $height :: $_POST['height']
  20.         $new_width = $width; // $width :: $_POST['width']
  21.        
  22.         // Get the original size
  23.         list($width, $height) = getimagesize($upload['tmp_name']);
  24.  
  25.         // creating a black image as representaion for the image new size
  26.         $t_image = imagecreatetruecolor($new_width, $new_height);
  27.  
  28.         // Creating the GD Image from uploaded image file
  29.         $gdImg = ($type =='image/png') ? imagecreatefrompng($upload['tmp_name']) : imagecreatefromjpeg($upload['tmp_name']);
  30.  
  31.         //Resizing the imgage
  32.         imagecopyresampled($t_image, $gdImg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  33.  
  34.         // The following scripts are just for saving the image files in a directory only
  35.  
  36.         //Remove the existing resized file
  37.         if(is_file('./upload/resized.png'))
  38.         unlink('./upload/resized.png');
  39.  
  40.         // saving the resized file in a directory as a PNG file
  41.         imagepng($t_image,__DIR__.'/upload/resized.png');
  42.         // destroying the created image after saving
  43.         imagedestroy($t_image);
  44.        
  45.  
  46.         //Remove the previous uploaded original file
  47.         if(is_file('./upload/original.png'))
  48.         unlink('./upload/original.png');
  49.  
  50.         // saving the original file in a directory as a PNG file
  51.         imagepng($gdImg,__DIR__.'/upload/original.png');
  52.         // destroying the created image after saving
  53.         imagedestroy($gdImg);
  54.        
  55.  
  56.         $_SESSION['flashdata']['type']="success";
  57.         $_SESSION['flashdata']['msg']="Image convertion is successfull.";
  58.  
  59.     }
  60.  
  61. }else{
  62.     $_SESSION['flashdata']['type']="danger";
  63.     $_SESSION['flashdata']['msg']="Image File is required.";
  64. }
  65. header("location:./");

The source code contains a comment script which can help you to understand more the process.

DEMO VIDEO

There you go. You can now test the source code you created on your end. If you encounter any errors please review the source code scripts above and see if you did miss something. You can also download the working source code I created for this tutorial. The download button is located below.

That ends this tutorial. I hope this will help you with what you are looking for and for your future projects. Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment