Reputation: 10867
I've been searching the internet for a while now and cannot find anything that tells me how I turn the result from $('#image-cropper').cropit('export')
into an image that PHP can upload to the server. I'm using the Cropit plugin and all I need is an image that I can pass into my php upload script. My code is as follows:
HTML:
<div id="image-cropper">
<input type="file" class="cropit-image-input" />
<div class="cropit-image-preview"></div>
<input type="range" class="cropit-image-zoom-input" />
<button class="export">Export</button>
</div>
jQuery:
var username = "<?php echo $userData['username']; ?>";
$('#image-cropper').cropit({
imageState:{
src:'users/'+username+'/profile_picture.jpg'
},
});
$('#image-cropper').cropit('previewSize', {width:500, height:500});
$('.export').click(function() {
var imageData = $('#image-cropper').cropit('export');
//$("#code").val(imageData);
window.open(imageData);
});
The code here is working properly for the plugin but I'm unable to turn the result which looks something like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD...
into an image that I can use in a php script. Any help would be great. Thanks!
Upvotes: 3
Views: 5660
Reputation: 10867
The way I got it to work is by messing around with the quality settings of Cropit and creating a PHP function that reads the base64 string and converts it to an image.
The code below is for cropit. I'm setting a timeout because if you don't it will send the form to php before cropit can create the base64. The base64 string is just stored in a text field which php can communicate based on $_POST
//Initiate Cropper
$('.image-editor').cropit();
//Assign Export Function
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export', {
type: 'image/jpeg',
quality: 0.33,
originalSize: true,
});
//Set value of hidden input to base64
$("#hidden_base64").val(imageData);
//Pause form submission until input is populated
window.setTimeout(function() {
document.upload_form.submit();
alert(imageData);
}, 1000);
});
The code below is for php. It works by decoding the base64 then moving it to a specified directory.
function decode ($code, $username) {
list($type, $code) = explode(';', $code);
list(, $code) = explode(',', $code);
$code = base64_decode($code);
file_put_contents('directory/filename.jpg', $code);
}
Upvotes: 6