Joe Scotto Joe Scotto - 1 year ago 956
Javascript Question

How to export image from cropit to php for upload?

I've been searching the internet for a while now and cannot find anything that tells me how I turn the result from

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:


<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>


var username = "<?php echo $userData['username']; ?>";

$('#image-cropper').cropit('previewSize', {width:500, height:500});

$('.export').click(function() {
var imageData = $('#image-cropper').cropit('export');

The code here is working properly for the plugin but I'm unable to turn the result which looks something like
into an image that I can use in a php script. Any help would be great. Thanks!

Answer Source

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

//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

    //Pause form submission until input is populated
    window.setTimeout(function() {
    }, 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);