Search code examples
javascriptjqueryjcrop

How to resize image to fit all the aspect ratio using jCrop?


I'm using Jcrop for resizing an image with aspect ratio 1. For most cases works well, however in some cases when the image is widther I can't select all the image. What kind of action can I do for select the whole content of the image?

enter image description here

My code is:

function readURL(input) {
if (input.files && input.files[0]) {
  var reader = new FileReader();
  reader.onload = function(e) {
    $('#jimage').attr('src', e.target.result);
  }

  reader.readAsDataURL(input.files[0]);
     $('#jimage').Jcrop({
        onSelect:    showCoords,
        aspectRatio: 1,
        bgColor:     '#2e7cce',
        bgOpacity:   .4,
        boxWidth: 500,
    });
}}

I tried to add some zoom implementations I looked in the web however the zoom affects the area of selection and the result is the same. I need to be able to select all the content of the image.


Solution

  • setting the aspectRatio: 1 means you always want a square selection, you would not be able to select the whole image if the image is rectangular(the height is bigger than width or vice versa).

    One solution is to remove aspectRatio: 1 this would allow free-form cropping.

    Another solution is to scale the image to a square before passing it on to Jcrop.

    reader.onload = function(e) {
      $('#jimage').attr('src', e.target.result);
      width = $('#jimage').width();
      height = $('#jimage').height();
      if(height > width )
        $('#jimage').width(width * (height/width));
      else if(width > height)
        $('#jimage').height(height * (width/height));
    }