工作 fiddle : http://jsfiddle.net/nbv8mb4a/
尝试 fiddle : http://jsfiddle.net/3m0zekyj/
我的工作 fiddle 允许用户在上传之前查看图像。接下来我尝试做的是获取要缩放的图像的高度和宽度,以便至少一侧为 160px,否则图像将缩放为 160px 或更大。
高度或宽度低于 160 的图像将被禁止,但我仍坚持获取宽度和高度。到目前为止我的工作代码如下;
var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function(){
readURL(this);
})
$('#file').click(function(){
fileInput.click();
}).show();
function readURL(input) {
$('#blah').hide();
if (input.files && input.files[0]) {
var goUpload = true;
var uploadFile = input.files[0];
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
$('#file').effect( "shake" );
$('#file').text('You must select an image file only');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (uploadFile.size > 2000000) { // 2mb
//common.notifyError('Please upload a smaller image, max size is 2 MB');
$('#file').text('Please upload a smaller image, max size is 2 MB');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (goUpload) {
$('#file').text("Uploading "+uploadFile.name);
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result).show();
$('#file').text(uploadFile.name);
}
reader.readAsDataURL(uploadFile);
}
}
}
最佳答案
在您尝试 fiddle 时,您正在调用:
width = this.width();
height = this.height();
,未定义。
首先分配 src 属性,然后读取宽度和高度,如下所示:
$('#blah').attr('src', e.target.result).show();
width = $('#blah').width();
height = $('#blah').height();
关于javascript - 如何获取高度和宽度或用户本地镜像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979612/