JCrop 无法正确裁剪图像
Posted
技术标签:
【中文标题】JCrop 无法正确裁剪图像【英文标题】:JCrop not cropping image properly 【发布时间】:2016-01-07 21:43:03 【问题描述】:我正在尝试使用 JCrop 裁剪图像,但是我保存到服务器上的图像是倾斜的。我似乎无法让尺寸正常工作。这是我的 JCrop 代码:
...
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'
);
请注意,#previewSub
是我正在裁剪的图像,#previewSub2
是正在裁剪的图像的缩略图(预览)。这是我的 JCrop 代码的其余部分:
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'
);
对于#x
、#y
、#w
、#y
,我不确定要为 val()
设置什么值。我尝试了各种组合,但我的裁剪总是关闭。
请注意,缩略图预览工作正常。
【问题讨论】:
【参考方案1】:我尝试使用您的代码并遇到了类似的问题。使用https://rubyplus.com/articles/3951-Cropping-Images-using-jCrop-jQuery-plugin-in-Rails-5 教程中的代码对我有用,它应该类似于下面的标准 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;
)();
还要确保如果您有强大的参数,则允许crop_x、crop_y、crop_h 和crop_w。
【讨论】:
以上是关于JCrop 无法正确裁剪图像的主要内容,如果未能解决你的问题,请参考以下文章