【发布时间】:2015-09-22 01:44:52
【问题描述】:
我目前正在开发一个简单的界面,允许用户上传图片,预览,然后将其裁剪为正方形。
我正在使用 FileReader 来获取图像的预览,并使用 jCrop 来裁剪它。
这是我正在使用的代码(其中的一部分):
var jcrop = null;
var reader = new FileReader();
reader.onload = function (e) {
$('#upload-picture-sample').attr('src', e.target.result).load(function(){
var img = this;
var imageWidth = img.width;
var imageHeight = img.height;
console.log(img.width+'-- WIDTH --'+$(this).width());
console.log(img.height+'-- HEIGHT --'+$(this).height());
if(imageWidth != imageHeight){
var selectArray = [];
if(imageWidth > imageHeight){
selectArray = [(imageWidth-imageHeight)/2, 0, (imageWidth-imageHeight)/2 + imageHeight, imageHeight];
}else{
selectArray = [0, (imageHeight - imageWidth)/2, imageWidth, (imageHeight - imageWidth)/2 + imageWidth];
}
if(!jcrop){
$('#upload-picture-sample').Jcrop({
aspectRatio: 1,
keySupport: false,
addClass: 'jcrop-centered',
setSelect: selectArray
}, function(){
jcrop = this;
});
}else{
jcrop.setImage(e.target.result);
jcrop.setSelect(selectArray);
}
}
$(this).unbind('load');
});
}
$('#upload-picture-file').change(function(){
$('#upload-picture-send').removeClass('disabled');
$('#upload-picture-error').hide();
console.log('changed!');
reader.readAsDataURL(this.files[0]);
})
我认为唯一真正重要的部分是我计算宽度和高度时的部分。
为了说明问题,我上传:
1/ 图片1 (600x450)
2/ 图片2 (94x125)
3/ 再次图片 1 (600x450)
第一次上传正常,第二次也正常,但我想这比其他事情更幸运,因为高度被错误地计算为 0。 第三次上传失败(大小设置不正确)。
表示cropzone没有正确显示。
关于css,我有这个:
#upload-picture-sample{
display:block;
margin-left: auto;
margin-right: auto;
margin-bottom: 30px;
max-height:125px;
height:auto;
width:auto;
max-width:300px;
}
您知道如何解决我的问题吗?
更新:按照@initialxy 的建议添加了setTimeout
所以它好多了,但是,第一张图像的尺寸与最后一张不同(它应该,因为它是完全相同的图像) 谢谢。
【问题讨论】:
标签: javascript jquery css filereader jcrop