如何从html 5文件API获取图像宽度

How to get the image width from html 5 file API

本文关键字:获取 图像 API 5文件 html      更新时间:2023-09-26

我正在尝试从图像拖放中获取图像宽度和高度,html 5 文件 api。 这就是我尝试获取宽度的方式:

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           
        }

    } 
} 

以像素为单位获取图像宽度和高度的正确方法是什么?

不能直接<input type=file>对象用作<img>源。

首先将其转换为数据URI:https://developer.mozilla.org/en/Using_files_from_web_applications#Example:_Using_object_URLs_to_display_images

此外,您还需要触发 Image.onload() 事件,然后才能尝试访问宽度值。