How to get crop the image using my own button?
I tried to execute this
var canvas = $selector.cropper('getCroppedCanvas')
but it's returning null value.
Is there a way to get the cropped canvas? And how can I put the cropped canvas data into <input type="file">
value and send it to PHP?
How to get crop the image using my own button?
I tried to execute this
var canvas = $selector.cropper('getCroppedCanvas')
but it's returning null value.
Is there a way to get the cropped canvas? And how can I put the cropped canvas data into <input type="file">
value and send it to PHP?
2 Answers
Reset to default 6Your selector should be the HTML container which contains the image: The Javascript and HTML should be like as mentioned below:
$img = $('#uploader-preview');
$img.cropper('getCroppedCanvas');
var canvaURL = canvas.toDataURL('image/jpeg'); // it returns the cropped image / canvas
<img src="" id="uploader-preview">
Send Canvas Image to PHP:
var photo = canvas.toDataURL('image/jpeg');
$.ajax({
method: 'POST',
url: 'photo_upload.php',
data: {
photo: photo
}
});
Here's PHP Script
photo_upload.php
<?php
$data = $_POST['photo'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
die;
?>
What is $selector? If it something like this:
var $selector = $(".selector");
Then you need call getCroppedCanvas() function to jQuery wrapper. Because if you write:
var canvas = $selector.cropper('getCroppedCanvas');
It calls cropper getCroppedCanvas function to DOM element, not to jQuery element.
Write something like this:
var $selector = $(".selector");
var canvas = $($selector).cropper('getCroppedCanvas');
And it will be work fine. If you want save canvas data as image on server, you can read this answer