PHP Image Resize and upload using jQuery AJAX

php image Javascript resize Image Before Upload

I have already wrote an article for image resizing in client side before it uploads to the server. In this post i am going to upload the resized image to the server. For that i have created “index.php”, “upload.php” and “images” folder under a directory in my local.

In index.php i have used HTML canvas to resize the image, once it is resized i am assigning the resized image source to “hidden_data” field in the form. When you click submit button the resized image source and files Object sent to the “upload.php”.

In “upload.php” i have used end, explode php functions to findout the image extension and replacing the data-type string from the base64 string. Once its replaced the file is ready to upload into the target directory that we have created using file_put_contents.

Please find below the source for index.php and upload.php files.

Index.php

<html>
<head>
<title>PHP Image Resize and upload using jQuery AJAX</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>
<form id="uploadForm" action="upload.php" method="post">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer">
<input name="imageFile" id="imageFile" type="file" class="inputFile" /><br/>
<input type="hidden" name="hidden_data" id="hidden_data" />
<br/>
<input type="submit" value="Submit" class="btnSubmit" />
</div>
</form>

	
</div>
 
<script type="text/javascript">

	$(document).ready(function (e) {
		
		function ResizeImage(dis) {
			var filesToUpload = document.getElementById('imageFile').files;
			var file = filesToUpload[0];
			 
			// Create an image
			var img = document.createElement("img");
			// Create a file reader
			var reader = new FileReader();
			// Set the image once loaded into file reader
			reader.onload = function(e) {
			//img.src = e.target.result;
			 
			var img = new Image();
			 
			img.src = this.result;
		 
			setTimeout(function(){
				var canvas = document.createElement("canvas");
				 
				var MAX_WIDTH = 300;
				var MAX_HEIGHT = 300;
				var width = img.width;
				var height = img.height;
				 
				if (width > height) {
					if (width > MAX_WIDTH) {
						height *= MAX_WIDTH / width;
						width = MAX_WIDTH;
					}
				} else {
					if (height > MAX_HEIGHT) {
						width *= MAX_HEIGHT / height;
						height = MAX_HEIGHT;
					}
				}
					canvas.width = width;
					canvas.height = height;
					var ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height);
					var dataurl = canvas.toDataURL("image/jpeg");
					//document.getElementById('output').src = dataurl;
					
					$("#hidden_data").val(dataurl);
					
					//console.log(canvas);
					
					$.ajax({
						url: "upload.php",
						type: "POST",
						data:  new FormData(dis),
						contentType: false,
						cache: false,
						processData:false,
						success: function(data)
						{
							$("#targetLayer").html(data);
						},
						error: function() 
						{
						} 	        
				   })
							
				},200);
				}
				// Load files into file reader
				console.log(file);
				
				reader.readAsDataURL(file);
			}
		
		
	$("#uploadForm").on('submit',(function(e) {
		e.preventDefault();
		
		//console.log("Form ", new FormData(this));
		ResizeImage(this);
			
	   //);
	}));
});
 
</script>

</body>
</html>

upload.php

<?php

if($_POST && $_FILES){
	$ext = end(explode(".",$_FILES['imageFile']['name']));

	$upload_dir = "images/";
	$img = $_POST['hidden_data'];
	if($ext == "png" || $ext == "PNG"){
		$img = str_replace('data:image/png;base64,', '', $img);
	}elseif($ext == "jpg" || $ext == "JPG" || $ext=="jpeg" || $ext =="JPEG"){
		$img = str_replace('data:image/jpeg;base64,', '', $img);
	}
	$img = str_replace(' ', '+', $img);
	$data = base64_decode($img);
	$file = $upload_dir . mktime() . ".".end(explode(".",$_FILES['imageFile']['name']));
	$success = file_put_contents($file, $data);
	print $success ? "<img src=".$file." border='0' />" : 'Unable to save the file.'; exit;
}else{
	print "Unable to process request"; exit;
}

?>

Hope this article help you for image resizing and uploading to the server.

Add a Comment

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