How to Create Multiple Thumbnails While Uploading Image

by Vincy. Last modified on July 3rd, 2022.

Generally, thumbnails are created to reduce the image dimensions and size. Creating thumbnails for the uploaded images is the good practice. By using thumbnails instead of the original image, it will help to contain them into the application layout. Also, the thumbnail image loading time will be optimistically lesser.

In this article, we are going to see how to create multiple thumbnails for an image uploaded by the user. Image upload and resize to thumbnails via programming is a most wanted code. If you searching for such code, this example will be helpful. Previously, we have seen how to create a single thumbnail by resizing the uploaded image.

In this example, I have used jQuery form library to upload image binary via AJAX. The ajax request will call the PHP code for creating thumbnails with the specified dimensions. Before creating thumbnails, the uploaded file will be validated to check if it is with the valid extension, allowed size.

After successful validation, the code to create multiple thumbnails will be executed. The created thumbnails are stored in a dynamically created target. PHP GD library functions are used to create thumbnail images programmatically.

How to Create Multiple Thumbnails while Uploading Image Output

Display Image Upload Option and Multiple Thumbnail Preview

This is the landing page which has the option to upload the image file. On choosing an image file by using this UI option, an AJAX function will be called. In this function, the image binaries are posted to the PHP file as specified with the AJAX parameter.

In this page, I have created a target container to display the thumbnail images of multiple dimensions. The default file input tag will be submerged with the choose button HTML by using CSS. The file input option contains the accept attribute to restrict the file type at the browser level. Also, I have handled the image validation on the server side using PHP.

<div id="form-container">
	<div id="imgContainer">
		<form enctype="multipart/form-data" action="image_upload_submit.php"
			method="post" name="image_upload_form" id="image_upload_form">

			<div id="selectImage">
				<div id="imgChange">
					<span>Choose Image</span> <input type="file" accept="image/*"
						name="image_file_input" id="image_file_input">
				</div>
			</div>

			<div class="progress-bar">
				<div class="percent">0%</div>
				<div class="bar"></div>
			</div>
		</form>
	</div>
	<br>
	<div class="img_preview" id="image-holder" style="display: none">
		<img width="150" height="93" id="small-preview" src="#"
			alt="small image" /> <img width="300" height="185"
			id="medium-preview" src="#" alt="medium image" /> <img width="550"
			height="340" id="large-preview" src="#" alt="big image" />
	</div>
</div>

jQuery Form Post via AJAX to Create Multiple Thumbnails

This script uses the jQuery form library to post the form with image data to the PHP endpoint. In this script, the upload progress is tracked and updated on the UI by using the uploadProgress callback. On successful AJAX response, the thumbnail path will be parsed from the AJAX response object and set to the preview target dynamically.

<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="vendor/jquery/jquery.form.min.js"></script>

<script>
$(document).on('change', '#image_file_input', function () {   
    var progressBar = $('.progress-bar');
	var bar = $('.progress-bar .bar'); 
	var percent = $('.progress-bar .percent');
    var percentVal;
    $('#image_upload_form').ajaxForm({
        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 = $.parseJSON(html);	
        		if(obj.status){		
        			percentVal = '100%';
        			bar.width(percentVal)
        			percent.html(percentVal);
        			$("#small-preview").prop('src',obj.small);		
        			$("#medium-preview").prop('src',obj.medium);		
        			$("#large-preview").prop('src',obj.large);		
        			$(".img_preview").show();	
        		}    
        }
    }).submit();		

});
</script>

Create Multiple Thumbnails in PHP

After posting the form data via AJAX, this PHP script will be executed to process the uploaded image. First, it validates the image size and dimension. Once the validation is completed, then the thumbnails will be created.

In this example, I have created three thumbnails with the dimensions 150X93, 300X185 and 550X340. The created thumbnail images are put into a dynamically created target folder.

The PHP functions for creating thumbnails and its target folder dynamically are defined in the functions.php file. This file will be imported on top of the PHP file which is called from AJAX. The thumbnails are created dynamically by using the PHP GD library functions.

<?php
require_once('functions.php');

if(isset($_FILES['image_file_input']))
{
    $output['status']=FALSE;
    set_time_limit(0);
    $allowedImageType = array("image/gif",   "image/jpeg",   "image/pjpeg",   "image/png",   "image/x-png"  );
    
    if ($_FILES['image_file_input']["error"] > 0) {
        $output['error']= "File Error";
    }
    elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
        $output['error']= "Invalid image format";
    }
    elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
        $output['error']= "Maximum file upload size is exceeded";
    } else {
        $temp_path = $_FILES['image_file_input']['tmp_name'];
        $file = pathinfo($_FILES['image_file_input']['name']);
        $fileType = $file["extension"];
        $fileName = rand(222, 888) . time() . ".$fileType";
        
        $small_thumbnail_path = "uploads/small/";
        createFolder($small_thumbnail_path);
        $small_thumbnail = $small_thumbnail_path . $fileName;
        
        $medium_thumbnail_path = "uploads/medium/";
        createFolder($medium_thumbnail_path);
        $medium_thumbnail = $medium_thumbnail_path . $fileName;
        
        $large_thumbnail_path = "uploads/large/";
        createFolder($large_thumbnail_path);
        $large_thumbnail = $large_thumbnail_path . $fileName;
        
        $thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 150, 93);
        $thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 300, 185);
        $thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 550, 340);
        
        if($thumb1 && $thumb2 && $thumb3) {
            $output['status']=TRUE;
            $output['small']= $small_thumbnail;
            $output['medium']= $medium_thumbnail;
            $output['large']= $large_thumbnail;
        }
    }
    echo json_encode($output);
}
?&gt

functions.php

<?php

function createFolder($path)
{
    if (! file_exists($path)) {
        mkdir($path, 0755, TRUE);
    }
}

function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight)
{
    if ($file_type == "png") {
        $source = imagecreatefrompng($sourcePath);
    } else {
        $source = imagecreatefromjpeg($sourcePath);
    }
    $width = imagesx($source);
    $height = imagesy($source);

    $tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);

    imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);

    if (imagejpeg($tnumbImage, $targetPath, 90)) {
        imagedestroy($tnumbImage);
        imagedestroy($source);
        return TRUE;
    } else {
        return FALSE;
    }
}
?>

Download

Comments to “How to Create Multiple Thumbnails While Uploading Image”

Leave a Reply to pamela Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page