JR Prajapati
19 Aug, 2018

How to crop image and upload it using jquery and php?

1 Answer         15198 Views

Jiwan Thapa
19 Aug, 2018

There are a lot of jquery plugins available for free that allow you to crop image. Let's see how we can do it using one of them namely croppie.

Integrate Jquery Plugin and Prepare HTML file to Add Image

Add the following links to your webpage, you can either download them and use locally or use the CDN directly.

https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.css
https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js

Now, Add HTML elements as required by the plugin. You can see it in the documentation. Here's the example of croppie as mentioned earlier with bootstrap classes included.

<div class="row">
	<div class="col-md-4">
		<div id="upload-image"></div>
	</div>
	<div class="col-md-4">
		<p>Select Image: <input type="file" id="images"></p>
		<p><button class="btn btn-success crop_image">Upload Image</button></p>
	</div>			
	<div class="col-md-4">
		<div id="upload-image-i"></div>
	</div>
</div>

Here, the entire width of the screen is divided into 3 equal width columns. The first column will hold the initial image with a slide ranger from where you can define the area of the image you want to crop. The second one will hold the button to choose file and upload it while the last colun will display the cropped image. The only thing you'll need to make the croppie function work is a bit of javascript now.

Add the following javascript code to your page or you can opt to create a new js file and put it there and link it to your page. Here's the code.

$image_crop = $('#upload-image').croppie({
	enableExif: true,
	viewport: {
		width: 200,
		height: 200,
		type: 'square'
	},
	boundary: {
		width: 300,
		height: 300
	}
});
$('#images').on('change', function () { 
	var reader = new FileReader();
	reader.onload = function (e) {
		$image_crop.croppie('bind', {
			url: e.target.result
		}).then(function(){
			console.log('jQuery bind complete');
		});			
	}
	reader.readAsDataURL(this.files[0]);
});

Here, the image data from id upload-image is stored in a variable $image_crop while enabling the image exchangeability so that the image size could be redefined when the croppie function is initialized. The viewport or the size of the cropped image is defined as 200 x 200 and the shape as square while the outer area of the container (boundary) is defined to be 300 x 300.

When the value of the id images changes which happens on the event an image is added to the input field, javascript function FileReader() is initialized which is used for filehandling in javascript and returns the data in byte format. On initialization of FileReader() function another function is initialized that binds all the event handlers present in the script and stores the data as a base64 encoded string.

So far, so good for the fronend. The image is cropped, now, let's save the cropped portion only to the database.

Send Cropped Image to PHP Function File Using Ajax

Here, we'll use ajax to store that cropped portion of the image to the database. Here's the ajax script.

$('.crop_image').on('click', function (ev) {		
	$image_crop.croppie('result', {
		type: 'canvas',
		size: 'viewport'
	}).then(function (response) {
		$.ajax({
			type:'POST',				 
			data: { image:response },
			url: "add-your-url-to-store-data-here",
			success: function (data) {					
				html = '<img src="' + response + '" >';
				$("#upload-image-i").html(html);
			}
		});
	});
});

Once the upload button is clicked, the data stored by the previous script along with its size is passed to the ajax function where the data sending method is defined as POST method and the data being sent is the response i.e. the base64 encoded string. The url of the page where the php code to handle this data should be stated and the action to be taken once the process is completed. Here, on successful execution of the event, the cropped image is being displayed inside the id upload-image-i but the best option would be to reload the page and display it in the desired place as page reload will remove the image from the first column as well. The script to reload the page is shown below.

success: function (data) {					
	location.reload();
}

Save Cropped Image in Database

Now, the final thing you need to do is add a php function that stores the data to the database as well as the cropped file in a folder inside the project directory.

$cropped_image = $_POST['image'];
list($type, $cropped_image) = explode(';', $cropped_image);
list(, $cropped_image) = explode(',', $cropped_image);
$cropped_image = base64_decode($cropped_image);
$image_name = date('ymdgis').'.png';
file_put_contents('Uploads/'.$image_name, $cropped_image);
// add insert/update query to save filename in the database table

Here, the image data sent using ajax is stored in a variable $cropped_image and the base64 encoded string is divided into two values by exploding it in the base of ";" and assigned to two separate variables. Again, the value stored in $cropped_image is separeted into two values where the last value is stored in $cropped_image itself. New name for the file and its extension is defined and the function file_put_contents() is called. This function is used to write data to a file and is identical to fopen(), fwrite() and fclose() combined successively. This function will create a file with the name defined in the defined location and add the data value from the variable $cropped_image. In this way, the temporary cropped image becomes a new image file. Now, the only thing remaining is to save the filename in the database.

Save Filename to Database

Once, the cropped image is stored in your project directory, saving that filename into the database won't be an issue. You can use the insert or update query as usual and pass the filename to get it saved in the database.


232 Likes         0 Dislike         0 Comment        


Leave a comment