user2896120 user2896120 - 4 months ago 14
Ajax Question

Ajax Cropped Image to PHP

I am trying to create a jQuery image cropper. A user will upload an image and an image preview of where they want to crop will be shown. The cropping size should be exactly 600 x 400. So if the user tries to upload an image that's 2000px wide by 2000px tall, then they will only be able to get a 600 x 400 selection of that image. After the user has selected their crop of that image, then they will be able to upload it. The cropped image should be relayed in Ajax and sent to PHP, but how do I create the Ajax for it? How can I send the cropped coordinates and the image dimensions through Ajax to PHP? Afterwards, how should the PHP look like? This plugin (cropbox) works on getting src's of images, but it's not working with input type="file" for some reason. Here's the jsfiddle, and here's what I've tried:

HTML

<input type="file" id="cropimage">


jQuery

$(function() {
var file = $("#cropimage").files[0];
if (file.type.match(/image\/.*/)) {
var reader = new FileReader();

reader.onload = function() {
var $img = $('<img />').attr({
src: reader.result
});
}
$img.on('load', function() {
$img.cropbox({
width: 600,
height: 400
}).on('cropbox', function(event, results, img) {

})

})
}
})

Answer
  • Attach change listener over file-input
  • Set reader.readAsDataURL(file);
  • Append $img in DOM
$(function() {
  $("#cropimage").on('change', function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function() {
      var $img = $('<img />').attr({
        src: reader.result
      });
      $img.on('load', function() {
        $img.cropbox({
          width: 600,
          height: 400
        }).on('cropbox', function(event, results, img) {});
      });
      $('body').append($img);
    };
    reader.readAsDataURL(file);
  });
});

Fiddle Demo