Darkroomjs Image Cropping发布到PHP

Does anybody know how to post the cropped image to PHP using darkroomjs?

Link here: https://github.com/MattKetmo/darkroomjs

I want to upload the cropped image to the server. Also, how do I set the location of the cropped image to appear in a different HTML element.

For example, if when I hit the crop button in darkroomjs it updates the cropper canvas with the new image. How do I make it also move the cropped image to another HTML element on the page?

Thanks in advance.

Theoretically, in order to post the image to PHP you want to get the src contents of the <img> element which is stored in Base64 in the case of this plugin.

Once you grab that value using JQuery, you can send it to the server asynchronously using AJAX or by posting your form the regular way by putting the src contents into a hidden field somewhere. From that point you can use tools such as PHP's GD and Image functions or Intervention / Image to create an image file on the server from that Base64 data.

In your case, sending it asynchronously by just grabbing the <img src="base64img"> would probably be easiest.

$('#theForm').submit(function(event){
     // preventDefault stops the regular synchronous submit from happening -- we don't want that. we want an async AJAX request
     event.preventDefault();

    var formData = $('#yourImgElement').attr('src');
    var returnMessage = '';

    $.post(site+'post/to/location', formData, function(response){
        if(response.status){
             returnMessage = 'Save Successful.';
        } else {
             returnMessage = 'Save Failed:

';

             for (i = 0; i < response.errors.length; i++) { 
                  returnMessage += '- ' + response.errors[i] + '
';
             }
        }

        alert(returnMessage);

     },'json');

     return false; // return false to cancel form action
  });

It's my understanding that cropping the image and saving it should reflect the changes within the Base64, but I personally and someone else is actually having problems with that.

In order to do the other stuff you want to do, you should be able to do it fairly easily with JQuery (look up restructuring the DOM). Just hook into the events:

// Post initialization method
initialize: function() {
    // Active crop selection
    this.plugins['crop'].requireFocus();

    // Add custom listener
    this.addEventListener('core:transformation', function() { 
         // THIS IS WHERE YOU WOULD THEN PERFORM DOM MANIPULATIONS USING JQUERY
     });
  }

You should be careful with moving the image after it's been edited, however. It could throw JavaScript errors if the plugin is expecting certain elements to be in certain locations.

UPDATED WITH SOLUTION:

======================

The src of the image will never change. In order to get the Base64 code of the edited image, you actually need to ask the canvas for it. Here is how you can do it:

// Plugins options
plugins: {
  crop: {
    //minHeight: 300,
    //minWidth: 400,
    //ratio: 4/3
  },
  save: {
      callback: function() {
          this.darkroom.selfDestroy(); // Turn off the bar and cleanup
          var newImage = dkrm.canvas.toDataURL();
          varThatStoresYourImageData = newImage;
      }
  }
}

I have a working version of this - it took me an hour or so to figure out and steal some other peoples suggestions mixed it all together and aletered a few bits here and there and here it is...

I parse the filename into JavaScript from my html from a hidden input type that was popuated by php ($('#profile_pic_filename').val();)

if($('.image-container.target').length){
    $('#member_portrait').change(function(){
        $('#member_photo_hidden_file').val("");
    });
    var pic_name = $('#profile_pic_filename').val();
    var dkrm = new Darkroom('#target', {
      // Size options
      minWidth: 100,
      minHeight: 100,
      maxWidth: 600,
      maxHeight: 500,
      ratio: 4/3,
      backgroundColor: '#000',
      // Plugins options
      plugins: {
        //save: false,
        crop: {
          quickCropKey: 67, //key "c"
          //minHeight: 50,
          //minWidth: 50,
          //ratio: 4/3
        },
        save: {
              callback: function() {
                  this.darkroom.selfDestroy(); // Cleanup
                  var newImage = dkrm.canvas.toDataURL();
                  $.ajax({
                    type     : "POST",
                    dataType : "html",
                    url      : base_url+'ajax/updateProfilePic',
                    data     : { 
                        'newImage'  : newImage,
                        'imageName' : pic_name
                    }
                })
                .done(function(response){
                    response   = $.parseJSON(response);
                    var status = response.status;
                    var data   = response.data;
                    if(status === "success"){
                        location.reload();
                    }else{
                        alert(data);
                    }
                });
              }
          }
      },
      // Post initialize script
      initialize: function() {
        var cropPlugin = this.plugins['crop'];
        // cropPlugin.selectZone(170, 25, 300, 300);
        cropPlugin.requireFocus();
      }
    });
}

in my ajax file i take the image and decode the base 64 version of the image and then parse that into a function with the filname that then overwrites the original file and hey presto the image has been replaced on the server.

$newImage  = '';
$imageName = '';
if(isset($_POST['newImage'])){
    $newImage = $_POST['newImage'];
}
if(isset($_POST['imageName'])){
    $imageName = $_POST['imageName'];
}
function saveProfilePic($filename,$filecontent){
    if (strlen($filename)>0){
        $folderPath = '/home/xxxxxxxxxxxxx/public_html/images/uploads/_mem_photo/';
        if (!file_exists($folderPath)) {
            mkdir($folderPath);
        }
        $file = @fopen($folderPath.$filename,"w");
        if($file != false){
            fwrite($file,$filecontent);
            fclose($file);
            return 1;
        }
        return -2;
    }
    return -1;
}
$data  = explode(',',$newImage);
$final = base64_decode($data[1]);
$fileSavingResult = saveProfilePic($imageName, $final);
if($fileSavingResult == 1){
    $return = array("status"=>"success", "data"=>"File was saved!");
} 
else if($fileSavingResult == -2){
    $return = array("status"=>"fail", "data"=>"An error occured during saving file!");
} 
else if($fileSavingResult == -1){
    $return = array("status"=>"fail", "data"=>"Wrong file name!");
}
echo json_encode($return);

I've just placed xxxxx into file path as I don't want to give up any server info.

If all is successfull you get a page reload and the newly transformed image loads on the page but if there is an error it will alert you.