Cropping Uploaded Image using Jcrop

Ganesh Babu picture Ganesh Babu · Apr 9, 2014 · Viewed 11.5k times · Source

I am trying to crop an uploaded image using Jcrop. My intention is to crop the image when the user upload. I need not store the user uploaded image in the server. But, I should store only the part of image user selects via Jcrop to the server. Here is the fiddle link for the problem

I have used the following code:

HTML:

<form id="form1">
    <input type='file' id="imgInp" />
    <img id="blah" class="crop" src="#" alt="your image" />
    <input type="hidden" id="x" name="x" />
        <input type="hidden" id="y" name="y" />
        <input type="hidden" id="w" name="w" />
        <input type="hidden" id="h" name="h" />
</form>

CSS:

<style>
#blah {
    background-color: #FFF;
    width: 500px;
    height: 330px;
    font-size: 24px;
    display: block;
  }
</style>

Js:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        console.log(this);
        readURL(this);
         $(function(){

    $('.crop').Jcrop({

      onSelect: updateCoords,

            bgOpacity:   .4,
            setSelect:   [ 100, 100, 50, 50 ],
            aspectRatio: 16 / 9
    });

  });
    });

  function updateCoords(c)
  {
    console.log(c);
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
  };

I tried like, after uploading image, the same image is used for JCrop, so that I can get the co-ordinate values to generate the rest of the image. My problem now is this: When uploaded, I get black color in the image spot rather than the uploaded image. Can anyone look into it and find what was wrong with the code?

Answer

David Stetler picture David Stetler · Apr 9, 2014

The problem with the image showing as black is occurring because you are calling jCrop on the image before it actually loads. You can put the call to jCrop after the reader.onload call so it will run after the image loads. See this :

reader.onload = function (e) {
     $('#blah').attr('src', e.target.result);
     $('.crop').Jcrop({       
         onSelect: updateCoords,
         bgOpacity:   .4,
         setSelect:   [ 100, 100, 50, 50 ],
         aspectRatio: 16 / 9
      });
}

Here is an updated fiddle