I am trying to crop an image using JCrop, however the image that I save on to my server is skewed. I can't seem to get the dimensions working properly. Here is my JCrop code:
...
var imgwidth = $("#previewSub2").width();
var imgheight = $("#previewSub2").height();
$("#previewSub").css("height", "220px");
$("#previewSub").css("width", "auto");
$("#previewSub").Jcrop({
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1,
setSelect: [0,imgwidth,0,0],
minSize: [90,90],
addClass: 'jcrop-light'
});
Note that #previewSub
is the image I am cropping, and #previewSub2
is the thumbnail (preview) for the image being cropped. Here is the rest of my JCrop code:
function showPreview(coords)
{
var imgSize = $("#previewSub").height();
var imgWidth = $("#previewSub").width();
var rx = 150 / coords.w;
var ry = 150 / coords.h;
$('#x').val(coords.x);
$('#y').val(coords.y);
$('#w').val(rx*imgWidth);
$('#h').val(ry*imgSize);
$('#previewSub2').css({
width: Math.round(rx * imgWidth) + 'px',
height: Math.round(ry * imgSize) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
For #x
, #y
, #w
, #y
, I am not really sure what values to put for val()
. I tried all sorts of combinations but my cropping is always off.
Note that the thumbnail preview works correctly.
I tried using your code and experienced a similar issue. Using the code from the tutorial at https://rubyplus.com/articles/3951-Cropping-Images-using-jCrop-jQuery-plugin-in-Rails-5 worked for me, which should be something like below as standard jQuery:
var ImageCropper,
bind = function(fn, me){ return function(){ return fn.apply(me,arguments); }; };
jQuery(function() {
return new ImageCropper();
});
ImageCropper = (function() {
function ImageCropper() {
this.updatePreview = bind(this.updatePreview, this);
this.update = bind(this.update, this);
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, 600, 600],
onSelect: this.update,
onChange: this.update
});
}
ImageCropper.prototype.update = function(coords) {
$('#course_crop_x').val(coords.x);
$('#course_crop_y').val(coords.y);
$('#course_crop_w').val(coords.w);
$('#course_crop_h').val(coords.h);
return this.updatePreview(coords);
};
ImageCropper.prototype.updatePreview = function(coords) {
return $('#preview').css({
width: Math.round(100 / coords.w * $('#cropbox').width()) + 'px',
height: Math.round(100 / coords.h * $('#cropbox').height()) + 'px',
marginLeft: '-' + Math.round(100 / coords.w * coords.x) + 'px',
marginTop: '-' + Math.round(100 / coords.h * coords.y) + 'px'
});
};
return ImageCropper;
})();
Also make sure that if you have strong parameters you permit crop_x, crop_y, crop_h and crop_w.