Upload Image and Create Multiple Thumbnails using PHP
Thumbnails are reduced-size versions of pictures or videos, used to help in recognizing and organizing. Thumbnails are ideally implemented on web pages as separate, smaller copies of the original image, in part because one purpose of a thumbnail image on a web application is to reduce bandwidth and download time. In this post, we have share how to Upload Image and Create Multiple Thumbnails using PHP. File upload functionality is one of the most common requirements for most web applications. This is a very simple example, you can just copy paste and change according to your requirement.
Before started to implement the NUpload Image and Create Multiple Thumbnails using PHP, look files structure:
- upload-image-and-create-multiple-thumbnails-php
- assets
- css
- style.css
- js
- jquery.form.min.js
- uploads
- _large
- _medium
- _mobile
- _thumb
- images
- css
- templates
- header.php
- footer.php
- index.php
- functions.php
- upload.php
- assets
Step 1: Create a function file
Create a file named functions.php
createFolder()
– create new foldergenerateThumbnail()
– create multiple Thumbnails
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php // create new folder function createFolder($path) { if (!file_exists($path)) { mkdir($path, 0755, TRUE); } } //create multiple Thumbnails function generateThumbnail($sourcePath, $targetPath, $fileType, $thumbWidth, $thumbHeight) { $source = imagecreatefromjpeg($sourcePath); $imgWidth = imagesx($source); $imgHeight = imagesy($source); $tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight); imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); if (imagejpeg($tnumbImage, $targetPath, 90)) { imagedestroy($tnumbImage); imagedestroy($source); return TRUE; } else { return FALSE; } } ?> |
Step 2: Create action file named
upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php // include functions require_once('functions.php'); // define root path $rootPath = "assets/uploads/"; $mobile_thumbnail_path = $rootPath . "_mobile/"; $thumb_thumbnail_path = $rootPath . "_thumb/"; $medium_thumbnail_path = $rootPath . "_medium/"; $large_thumbnail_path = $rootPath . "_large/"; if(isset($_FILES['upl_file'])) { $output['status']=FALSE; $allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" ); if ($_FILES['upl_file']["error"] > 0) { $output['error']= "File uploading Error"; } elseif (!in_array($_FILES['upl_file']["type"], $allowedImageType)) { $output['error']= "Incorrect image format"; } elseif (round($_FILES['upl_file']["size"] / 1024) > 4096) { $output['error']= "Uploaded file is too large."; } else { $temp_path = $_FILES['upl_file']['tmp_name']; $file = pathinfo($_FILES['upl_file']['name']); $fileExtension = $file["extension"]; $fileName = rand(111, 999) . time() . ".$fileExtension"; createFolder($mobile_thumbnail_path); $mobile_thumbnail = $mobile_thumbnail_path . $fileName; createFolder($thumb_thumbnail_path); $thumb_thumbnail = $thumb_thumbnail_path . $fileName; createFolder($medium_thumbnail_path); $medium_thumbnail = $medium_thumbnail_path . $fileName; createFolder($large_thumbnail_path); $large_thumbnail = $large_thumbnail_path . $fileName; $mobile = generateThumbnail($temp_path, $mobile_thumbnail, $fileExtension, 110, 70); $thumb = generateThumbnail($temp_path, $thumb_thumbnail, $fileExtension, 150, 100); $medium = generateThumbnail($temp_path, $medium_thumbnail, $fileExtension, 290, 170); $large = generateThumbnail($temp_path, $large_thumbnail, $fileExtension, 500, 300); if($mobile && $thumb && $medium && $large) { $output['status']=TRUE; $output['mobile']= $mobile_thumbnail; $output['thumb']= $thumb_thumbnail; $output['medium']= $medium_thumbnail; $output['large']= $large_thumbnail; } } echo json_encode($output); } ?> |
jQuery code handle AJAX request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<script> jQuery(document).on('change', 'input#upload-img', function () { var progressBar = jQuery('.progress-bar'); var bar = jQuery('.progress-bar .bar'); var percent = jQuery('.progress-bar .percent'); var percentVal; jQuery('#img_upload_form').ajaxForm({ type: 'POST', url: 'upload.php', beforeSend: function() { progressBar.fadeIn(); percentVal = '0%'; bar.width(percentVal) percent.html(percentVal); }, uploadProgress: function(event, position, total, percentComplete) { percentVal = percentComplete + '%'; bar.width(percentVal) percent.html(percentVal); }, success: function(html, statusText, xhr, $form) { obj = jQuery.parseJSON(html); if(obj.status){ percentVal = '100%'; bar.width(percentVal) percent.html(percentVal); jQuery("#_mobile-preview").prop('src',obj.mobile); jQuery("#_thumb-preview").prop('src',obj.thumb); jQuery("#_medium-preview").prop('src',obj.medium); jQuery("#_large-preview").prop('src',obj.large); jQuery(".img_preview").show(); } } }).submit(); }); </script> |
Step 3: Create HTML file named
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?php include('templates/header.php');?> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Upload Image and Create Multiple Thumbnails using PHP</h2> </div> <form method="POST" name="img_upload_form" id="img_upload_form" enctype="multipart/form-data"> <div class="row align-items-center"> <div class="form-group col-md-9"> <label for="inputEmail4">Choose a file:</label> <input type="file" accept="image/*" name="upl_file" id="upload-img"> <span id="chk-error"></span> </div> </div> </form> <hr> <div class="row align-items-center"> <div class="col"> <div class="progress progress-bar"> <div id="file-progress-bar" class="bar percent">%0</div> </div> </div> </div> <div class="row align-items-center"> <div class="col-md-12"> <hr> <div class="img_preview" id="image-holder" style="display: none;"> <img width="110" height="70" id="_mobile-preview" src="#" alt="for Mobile" /> <img width="150" height="100" id="_thumb-preview" src="#" alt="for Thumbnails" /> <img width="290" height="170" id="_medium-preview" src="#" alt="for Medium" /> <img width="500" height="300" id="_large-preview" src="#" alt="for Large" /> </div> </div> </div> </div> </section> <?php include('templates/footer.php');?> <script> jQuery(document).on('change', 'input#upload-img', function () { var progressBar = jQuery('.progress-bar'); var bar = jQuery('.progress-bar .bar'); var percent = jQuery('.progress-bar .percent'); var percentVal; jQuery('#img_upload_form').ajaxForm({ type: 'POST', url: 'upload.php', beforeSend: function() { progressBar.fadeIn(); percentVal = '0%'; bar.width(percentVal) percent.html(percentVal); }, uploadProgress: function(event, position, total, percentComplete) { percentVal = percentComplete + '%'; bar.width(percentVal) percent.html(percentVal); }, success: function(html, statusText, xhr, $form) { obj = jQuery.parseJSON(html); if(obj.status){ percentVal = '100%'; bar.width(percentVal) percent.html(percentVal); jQuery("#_mobile-preview").prop('src',obj.mobile); jQuery("#_thumb-preview").prop('src',obj.thumb); jQuery("#_medium-preview").prop('src',obj.medium); jQuery("#_large-preview").prop('src',obj.large); jQuery(".img_preview").show(); } } }).submit(); }); </script> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Upload Image and Create Multiple Thumbnails using PHP | Tech Arise</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="assets/js/jquery.form.min.js"></script> </body> </html> |