javascriptphpjquerybootstrap-4croppie

Can I use Javascript to Rotate and Crop a gallery of images prior to upload?


I've been trying to use the file reader and croppie to allow users to edit their images locally (zoom / rotate / crop) prior to upload, but can't seem to get it to work correctly. I am suspecting this is a DOM issue because of the modal, but I can't for the life of me figure out how to make it work!


FileReader () stuff
//
//
//create elements for image, edit and delete buttons, then appending to parent div
//
//

//place the new image and button into the new div
newdiv.appendChild(newimage);
newdiv.appendChild(newedit);
newdiv.appendChild(newdelete);

//place the new div into the results div
output.appendChild(newdiv);

//add event listeners to dynamically created buttons
newdelete.addEventListener('click', delImage, false);
newedit.addEventListener('click', showModal, false);

.
.
.

function showModal(){
    var edit_id = this.getAttribute("dataset-editid");
    var image_id = document.getElementById('img-'+edit_id);
    var thisImage = image_id.src;
    $('#'+edit_id).click(function(){
        $("#cropImagePop").modal();
    });
    console.log(edit_id);
    console.log('image source: ' + image_id);
    var themodal = document.getElementById('cropImagePop');
    var theimage = document.getElementById('cropimage');
    var instance = new Croppie(theimage, {
        viewport: { width: 300, height: 300 },
        boundary: { width: 900, height: 600 },
        showZoomer: true,
        enableResize: true,
        url: thisImage
    });

}

When I click the dynamic 'edit' button for any given picture the modal opens, but the photo is really large (not staying within the modal), and there is not a bounding box to crop to..

Here is a fiddle: https://jsfiddle.net/noz2eb3y/

Also - I am by no means married to Croppie - if someone has a great (working!) javascript library they know of which can zoom/rotate/crop images - I'm all ears!


Solution

  • To answer your question: Yes it is possible.

    The issue with the modal window is because you forgot to add the croppie css reference.

    I fixed that in this fiddle and also added a function to the crop button, to update the source element.

    See the following example:

    $('#cropImageBtn').click(function(){
      instance.result('base64').then(function(base64) {
        image_id.src = base64;
        cleanModal();
      });
    });
    $('#closeImageBtn').click(function(){
        cleanModal();
    });
    function cleanModal()
    {
      instance.destroy();
      $("#cropImagePop").modal("hide");
    }
    

    Next steps you need to take if you want to upload the image(s).

    1. Take a look at jquery.ajax
    2. Post the base64 encoded data to your server
    3. Decode the base64 encoded data
    4. Save the image file

    I'd also recommend to improve your code (it's a bit mixed up).