如何从HTML 5文件API获取图像宽度 [英] How to get the image width from html 5 file API

查看:114
本文介绍了如何从HTML 5文件API获取图像宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从图像拖放中获取图像宽度和高度,html 5文件api。这是我如何获得宽度:

pre $函数process_drop(evt){

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

//单独运行每个文件。
for(var i = 0,f; f = files [i]; i ++){

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

//检查是否为图片
if(f.type.match('image。*')){
console.log('this is a image' + f.type);

//尝试获取文件宽度
var img = new Image();
img.src = f;
console.log('img.width ='+ img.width); //无效




$ $ $ $ $ $ $ $ $ $

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

解决方案

直接作为< img> 的来源< code>< input type = file>
$ b

首先将其转换为dataURI: https://开发者。您还需要先触发Image.onload()事件,然后才能尝试访问宽度值(例如, 。


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?

解决方案

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.

这篇关于如何从HTML 5文件API获取图像宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆