Javascript获取图像宽度,高度和视频的分辨率

时间:2016-08-14 13:34:33

标签: javascript jquery

这是我的代码:

if($('#profileimg').val())
    {
        var fsize = $('#profileimg')[0].files[0].size; //get file size
        var ftype = $('#profileimg')[0].files[0].type; // get file type
        if(fsize>5242880) 
        {
            $("#filetype").html("<b> Profile Image "+bytesToSize(fsize) +"</b>  <br />File is too big, it should be less than 5 MB.");
            return false
        }
        if(filetypeimage(ftype))
        {
            var file, img;
        if ((file = $('#profileimg')[0])) {
        img = new Image();
        img.onload = function() {
            alert(this.width + " " + this.height);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);


        }

我想获取图像的宽度和高度,我也希望获得将在我们的服务器上传的视频分辨率。

提前致谢

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
window.URL = window.URL || window.webkitURL;


$('#submit').on('click',function(e){
    e.preventDefault(); 
    var fileInput = $('#file')[0],
        file = fileInput.files && fileInput.files[0];

    if( file ) {
        var img = new Image();
        img.src = window.URL.createObjectURL( file );
        img.onload = function() {
            var width = img.naturalWidth,
                height = img.naturalHeight;

            window.URL.revokeObjectURL( img.src );
            alert(width +" "+  height);
        };
    }    

});


// you can validate on file change also
$("#file").change(function(e) {
    var file, img;

    if ((file = this.files[0])) {        
        img = new Image();
        console.log(this);
        img.onload = function() {
            alert(this.width + " " + this.height);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = window.URL.createObjectURL(file);

    }
});
&#13;
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post">
    <input type="file" id="file" />
    <input type="submit" id="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html> 
&#13;
&#13;
&#13;