jQuery Ajax Image Resize with Aspect Ratio

In this tutorial, we are going to see how to resize the uploaded image with the aspect ratio. The aspect ratio will be calculated by using the dimensions of the original image. Based on this aspect ratio the width or height of the thumbnail image will be scaled. 

In this tutorial, I have used jQuery AJAX to access the image resize function in a PHP class. In a previous tutorial, we have seen the code example for uploading image file via jQuery AJAX. In this example, the image file data is sent to the PHP to access ImageResizer service. On successful image resizing, the PHP code will return the thumbnail markup as a response.

jquery-ajax-image-upload

HTML Form to Submit Image Data

This code shows HTML to upload the image file to be resized via jquery AJAX function. On clicking the Upload Photo button the selected file input data is sent to a PHP file via AJAX request.

<form id="uploadForm" action="upload.php" method="post">
	<div id="targetOuter">
		<div id="targetLayer"></div>
		<img src="photo.png" class="icon-choose-image" />
		<div class="icon-choose-image">
			<input name="userImage" id="userImage" type="file" class="inputFile"
				onChange="showPreview(this);" />
		</div>
	</div>
	<div>
		<input type="submit" value="Upload Photo" class="btnSubmit" />
</form>

Access ImageResizer via jQuery AJAX

This jQuery function sends an AJAX request to PHP by passing the image data. In PHP code, it accesses ImageResizer service to create thumb based on the aspect ratio.  The AJAX call will get the resized image markup after resizing is done.

<script type="text/javascript">
function showPreview(objFileInput) {
    if (objFileInput.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (e) {
            $("#targetLayer").html('<img src="'+e.target.result+'" class="upload-preview" />');
			$("#targetLayer").css('opacity','0.7');
			$(".icon-choose-image").css('opacity','0.5');
        }
		fileReader.readAsDataURL(objFileInput.files[0]);
    }
}

$(document).ready(function (e) {
	$("#uploadForm").on('submit',(function(e) {
		e.preventDefault();
		$.ajax({
        	url: "upload.php",
			type: "POST",
			data:  new FormData(this),
			beforeSend: function(){$("#body-overlay").show();},
			contentType: false,
    	    processData:false,
			success: function(data)
		    {
			$("#targetLayer").html(data);
			$("#targetLayer").css('opacity','1');
			setInterval(function() {$("#body-overlay").hide(); },500);
			},
		  	error: function() 
	    	{
	    	} 	        
	   });
	}));
});
</script>

ImageResizer Service

In the ImageResizer class, I define a function to resize the original image based on the aspect ratio. If the width and height of the original image are not same, then the aspect ratio is calculated to scale down or scale up the thumbnail image dimensions.

<?php
class ImageResizer
{
    private $thumbWidth = "550";
    private $thumbHeight = "340";
    
    function createThumbnail($image_name)
    {
        $sourcePath = $uploadDir . '/' . $image_name;
        
        $sourcePathinfo = getimagesize($sourcePath);
        $imageDetail = pathinfo($sourcePath);
        
        $originalImage = imagecreatefromjpeg($sourcePath);
        
        $width          =   $imageDetail["width"];
        $height          =   $imageDetail["height"];
        
        if($width > $height)
        {
            $thumbWidth    =   $this->$thumbWidth;
            $thumbHeight    =   $old_y*($this->$thumbHeight/$old_x);
        }
        
        if($width < $height)
        {
            $thumbWidth    =   $old_x*($this->$thumbWidth/$old_y);
            $thumbHeight    =   $this->$thumbHeight;
        }
        
        if($width == $height)
        {
            $thumbWidth    =   $this->$thumbWidth;
            $thumbHeight    =   $this->$thumbHeight;
        }
        
        $thumbImage  =   ImageCreateTrueColor($thumbWidth,$thumbHeight);
        
        imagecopyresampled($thumbImage,$originalImage,0,0,0,0,$thumbWidth,$thumbHeight,$width,$height);
        
        
        // New save location
        $targetPath = $moveToDir . $image_name;
        
        $result = imagejpeg($thumb_image,$targetPath,80);
        
        imagedestroy($thumbImage);
        imagedestroy($originalImage);
        
        return $result;
    }
}
?>

Download

This jQuery code tutorial was published on September 26, 2017.

↑ Back to Top