Skip to main content

Resizing the Uploaded Image in PHP using GD extension Tutorial

Screenshot
Body

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