Optimizing the Uploaded Image in PHP Tutorial

In this tutorial, I will show you a way how to upload images in PHP with reduced quality and resized resolution. This kind of feature might be helpful to your current or future project that uploads and displays lots of images. It will help your project load the pages faster even there are a lot of images are being shown because instead of displaying the original size and quality of the images is optimized. For example, you are developing a Blog Site and each blog or article has a thumbnail or banner image. On your list page, you want to display the thumbnails or images of the articles listed. So, instead of displaying the image that has the original size and resolution, you can display the optimized images so that the list page will load faster even though lots of images are being loaded on the page.

In this article, I will show you a simple web program that contains an uploading feature and displays it. The application will also upload the original copy of the image and creates an optimized copy and save them both in different directories. I will be using a MySQL Database to store the images paths. Uploaded optimized images will be loaded on the right side of the panel with the links displaying the original and optimized images so you can compare. The source code only reduces the quality of the low-resolution images. The system will only create a resized copy of the uploaded image that is larger than 640x480 pixels resolution.

Getting Started

Download the following to your local machine:

  • The latest version of XAMPP

Install the XAMPP into your local machine. Next, open the XAMPP's php.ini file and uncomment GD Library extension to enable it. After that, open the XAMPP's Control Panel and start the Apache and MySQL Server.

Open your preferred browser and browse the XAMPP's PHPMyAdmin by browsing http://localhost/phpmyadmin.

Creating the Database

Create a new database naming dummy_db. After that, navigate the page into the SQL tab of your newly created database. Then, paste the SQL Script below into the provided text field and click the Go button below to execute the SQL Script.

  1. CREATE TABLE `uploaded_files` (
  2. `original_path` text NOT NULL,
  3. `thumbnail_path` text NOT NULL

Creating the Database Connection File

Open your preferred text editor such as notepadd++ or sublime text. Create a new PHP File naming db-connect.php. Save the file inside your source code directory's root path. Then, copy/paste the script below.

  1.  
  2. <?php
  3. $host = 'localhost';
  4. $username = 'root';
  5. $pw = '';
  6. $dbname = 'dummy_db';
  7.  
  8. $conn = new mysqli($host, $username, $pw, $dbname);
  9. if(!$conn){
  10. die("Cannot connect to the database. Error:". $conn->error);
  11. }

Creating the Interface

Next, create a new PHP File naming index.php. This file contains the scripts of displaying the elements of the application. I contains the uploading form and display area of the uploaded images. Uploaded images will only display the optimized images.

  1. <?php require_once('db-connect.php'); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Optimzing Uploaded Images</title>
  8. </head>
  9. html, body{
  10. width:100%;
  11. margin:unset;
  12. }
  13. .text-center{
  14. text-align:center;
  15. }
  16. .panel-row{
  17. width:100%;
  18. display:flex;
  19. padding: 0 15px;
  20. }
  21. .left-panel{
  22. width:30%;
  23. padding: .5rem;
  24. min-height:10rem;
  25. border-radius:.5rem;
  26. }
  27. .right-panel{
  28. width:70%;
  29. padding: .5rem;
  30. display:flex;
  31. flex-wrap:wrap;
  32. }
  33. input[type="file"]{
  34. width:100%;
  35. }
  36. .img-holder{
  37. width:20%;
  38. height:15vh;
  39. padding:.5em;
  40. margin-bottom:1.8em
  41. }
  42. .img-holder>img{
  43. width:100%;
  44. height:100%;
  45. object-fit:scale-down;
  46. object-position:center;
  47. background: #000c;
  48. }
  49. @media (max-width:680px){
  50. .panel-row{
  51. flex-direction:column
  52. }
  53. .left-panel, .right-panel{
  54. width:100%;
  55. }
  56. .img-holder{
  57. width:90%;
  58. height:40vh;
  59. }
  60. }
  61. <h2 class="text-center">Optimizig Uploaded Images</h2>
  62. <hr>
  63. <div class="panel-row">
  64. <div class="left-panel">
  65. <form action="upload.php" method="POST" enctype="multipart/form-data">
  66. <h4 class="text-center"><b>Upload Image</b></h4>
  67. <input type="file" name="img" accept="image/png, image/jpeg" required>
  68. <small><i>Accepts only PNG and JPEG Files</i></small>
  69. <br>
  70. <br>
  71. <button>Upload</button>
  72. </center>
  73. </form>
  74. </div>
  75. <div class="right-panel">
  76. <?php
  77. $query = $conn->query("SELECT * FROM `uploaded_files`");
  78. while($row = $query->fetch_assoc()):
  79. ?>
  80. <div class="img-holder">
  81. <img src="<?= $row['thumbnail_path'] ?>" alt="">
  82. <br>
  83. <div class="text-center"><a href="<?= $row['original_path'] ?>" target="_blank">Original</a></div>
  84. <div class="text-center"><a href="<?= $row['thumbnail_path'] ?>" target="_blank">Optimized</a></div>
  85. </div>
  86. <?php endwhile; ?>
  87. </div>
  88. </div>
  89. <?php $conn->close(); ?>
  90. </body>
  91. </html>

Creating the Upload Script

Lastly, create a new PHP File naming upload.php. This is where the main scripts for our goal on this tutorial be found. The below PHP Script contains the uploading the original and optimized copies of the image. This contains also the code of saving the paths of the images in the database.

  1. <?php
  2. require_once('db-connect.php');
  3. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  4. if(isset($_FILES['img']) && !empty($_FILES['img']['tmp_name'])){
  5. $img = $_FILES['img'];
  6. // Orginal uploaded images directory
  7. $original_dir = "originals/";
  8. //Creating Directory if not exists
  9. if(!is_dir($original_dir))
  10. mkdir($original_dir);
  11.  
  12. // uploaded images thumbnail directory
  13. $thumbnail_dir = "thumbnails/";
  14. //Creating Directory if not exists
  15. if(!is_dir($thumbnail_dir))
  16. mkdir($thumbnail_dir);
  17.  
  18. //FileName
  19. $fname = $img['name'];
  20.  
  21. // Checking Duplicate Filename
  22. $i = 0;
  23. while(true){
  24. if($i == 0){
  25. if(!is_file($original_dir.$fname) && !is_file($thumbnail_dir.$fname)){
  26. break;
  27. }
  28. }else{
  29. if(!is_file($original_dir.$i."_".$fname) && !is_file($thumbnail_dir.$i."_".$fname)){
  30. $fname = $i."_".$fname;
  31. break;
  32. }
  33. }
  34. $i++;
  35. }
  36. // Image File Type
  37. $file_type = mime_content_type($img['tmp_name']);
  38. $oupload = false;
  39. $thumb_upload = false;
  40.  
  41. if($file_type=='image/png'){
  42. // For PNG Files
  43. $gdimg= imagecreatefrompng($img['tmp_name']);
  44. if($gdimg){
  45. $oupload = imagepng($gdimg,$original_dir.$fname,9);
  46. list($width, $height) =getimagesize($img['tmp_name']);
  47. if($width > 640 || $height > 480){
  48. if($width > $height){
  49. $perc = ($width - 640) / $width;
  50. $width = 640;
  51. $height = $height - ($height * $perc);
  52. }else{
  53. $perc = ($height - 480) / $height;
  54. $height = 480;
  55. $width = $width - ($width * $perc);
  56. }
  57. }
  58. $gdimg = imagescale($gdimg, $width, $height);
  59. $thumb_upload = imagepng($gdimg,$thumbnail_dir.$fname,6);
  60. imagedestroy($gdimg);
  61. }else{
  62. echo '<script>alert("Invalid PNG File.")</script>';
  63. }
  64. }else if($file_type == 'image/jpeg'){
  65. // For JPEG Files
  66. $gdimg= imagecreatefromjpeg($img['tmp_name']);
  67. if($gdimg){
  68. $oupload = imagejpeg($gdimg,$original_dir.$fname,100);
  69. list($width, $height) =getimagesize($img['tmp_name']);
  70. if($width > 640 || $height > 480){
  71. if($width > $height){
  72. $perc = ($width - 640) / $width;
  73. $width = 640;
  74. $height = $height - ($height * $perc);
  75. }else{
  76. $perc = ($height - 480) / $height;
  77. $height = 480;
  78. $width = $width - ($width * $perc);
  79. }
  80. }
  81. $gdimg = imagescale($gdimg, $width, $height);
  82. $thumb_upload = imagejpeg($gdimg,$thumbnail_dir.$fname,50);
  83. imagedestroy($gdimg);
  84. }else{
  85. echo '<script>alert("Invalid JPEG File.")</script>';
  86. }
  87. }else{
  88. echo '<script>alert("Invalid Image type.")</script>';
  89. }
  90. if($oupload && $thumb_upload){
  91. $sql = "INSERT INTO `uploaded_files` (`original_path`, `thumbnail_path`) VALUES ('{$original_dir}{$fname}', '{$thumbnail_dir}{$fname}') ";
  92. $save = $conn->query($sql);
  93. if($save){
  94. echo '<script>alert("Image has been uploaded successfully.")</script>';
  95. }else{
  96. if(is_file($original_dir.$fname))
  97. unlink($original_dir.$fname);
  98. if(is_file($thumbnail_dir.$fname))
  99. unlink($thumbnail_dir.$fname);
  100. echo 'Uploading Image Failed <br>';
  101. echo 'Error: '. $conn->error;
  102. }
  103. }else{
  104. echo 'Uploading Image Failed <br>';
  105. }
  106.  
  107. }else{
  108. echo '<script>alert("No Image file has been sent.")</script>';
  109. }
  110. }else{
  111. echo '<script>alert("No Data has been sent.")</script>';
  112. }
  113.  
  114. $conn->close();
  115. echo '<script>location.replace("./")</script>';
  116. ?>

That's it! You can now check the application and see if it works as we planned and if it achieves our goal of this tutorial. You can test the application by browsing http://localhost/source_code_directory_name/ in to your preferred browser.

DEMO VIDEO

That's the end of this tutorial. If there's an error occurred on your end, please review your changes to your codes and try to differentiate them from the source code I provided above. You can also download the working source code I created for this tutorial. The download button is located below this article.

I hope this tutorial will help you with what you are looking for and you'll find this useful for your future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Add new comment