How to get the image width from html 5 file API

2020-07-30 05:08发布

I am trying to get the image width and height from a image drag and drop, html 5 file api. This is how I am trying to get the width:

function process_drop(evt) {

        evt.stopPropagation(); 
        evt.preventDefault(); 
        var files = evt.dataTransfer.files; 

    // run through each file individually.
    for (var i = 0, f; f = files[i]; i++) {

        console.log('file_size=' + f.size);

        // check if it is an image          
        if (f.type.match('image.*')) {
            console.log('this is an image ' + f.type);

            //try to get the file width
            var img = new Image();           
            img.src = f;
            console.log('img.width=' + img.width); //does not work           
        }


    } 
} 

What is the proper way to get the image width and height in pixels?

1条回答
我想做一个坏孩纸
2楼-- · 2020-07-30 05:16

You cannot use <input type=file> object directly as the source of <img>.

First convert it to dataURI: https://developer.mozilla.org/en/Using_files_from_web_applications#Example:_Using_object_URLs_to_display_images

Also you need to have Image.onload() event triggered before you can try to access width value.

查看更多
登录 后发表回答