简体   繁体   English

如何获取高度和宽度或用户本地图像

[英]How to get height and width or users local image

Working Fiddle: http://jsfiddle.net/nbv8mb4a/ 工作小提琴: http : //jsfiddle.net/nbv8mb4a/

Attempted Fiddle: http://jsfiddle.net/3m0zekyj/ 尝试小提琴: http : //jsfiddle.net/3m0zekyj/

My working Fiddle allows the user to see the image before uploading. 我正在使用的小提琴使用户可以在上传之前查看图像。 What I am attempting to do next is to obtain the height and width of the image to scale so that at least one side is 160px whereas the otherwise will be 160px or greater the image will scale. 我接下来要尝试的是获取要缩放的图像的高度和宽度,以便至少一侧为160px,否则将为160px或更大。

Images lower than 160 height or width will not be allowed however I'm stuck on my tracks to get the width and height. 高度或宽度小于160的图像将不被允许,但是我被困在轨道上以获取宽度和高度。 My working code so far is below; 到目前为止,我的工作代码如下;

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);
        }
    }
}

Some Progress: http://jsfiddle.net/pe8wg9kx/ 一些进展: http : //jsfiddle.net/pe8wg9kx/

In your attempted fiddle you are calling: 在您尝试的小提琴中,您正在呼叫:

width = this.width(); 
height = this.height();

, which are undefined. ,这是未定义的。
First assign the src attribute and then read width and height like this: 首先分配src属性,然后读取宽度和高度,如下所示:

$('#blah').attr('src', e.target.result).show();
width = $('#blah').width(); 
height = $('#blah').height();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM