HTML5 - 如何获取图片尺寸 [英] HTML5 - how to get image dimension

查看:118
本文介绍了HTML5 - 如何获取图片尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本,它用来获取浏览器上传图片的宽度和高度。

参考: http://renevier.net /misc/resizeimg.html

  function createReader(file){
reader.onload = function( evt){
var image = new Image();
image.onload = function(evt){
var width = this.width;
var height = this.height;
alert(width); //会产生类似198
}的东西;
image.src = evt.target.result;
};
reader.readAsDataURL(file);
}

for(var i = 0,length = input.files.length; i< length; i ++){
createReader(input.files [i]);
}

我想从<$ c $外部访问数值宽度和高度c> createReader 功能。我怎样才能做到这一点?

解决方案

更改createReader,以便传递一个处理函数,可用:

 函数createReader(file,whenReady){
reader.onload = function(evt){
var image = new Image();
image.onload = function(evt){
var width = this.width;
var height = this.height;
if(whenReady)whenReady(width,height);
};
image.src = evt.target.result;
};
reader.readAsDataURL(file);
}

现在当你调用它的时候,你可以传入一个函数来做任何事情你想要完成图像尺寸:

  createReader(input.files [i],function(w,h){
alert(你好宽度是+ w +,高度是+ h);
});


I have this script, it's used to fetch the width and the height of browser uploaded image.

reference: http://renevier.net/misc/resizeimg.html

function createReader(file) {
    reader.onload = function(evt) {
        var image = new Image();
        image.onload = function(evt) {
            var width = this.width;
            var height = this.height;
            alert (width); // will produce something like 198
        };
        image.src = evt.target.result; 
    };
    reader.readAsDataURL(file);
}

for (var i = 0, length = input.files.length; i < length; i++) {
    createReader(input.files[i]);
}

I want to access the value width and height from outside the createReader function. How can I do that?

解决方案

Change "createReader" so that you pass in a handler function to be called when the image is available:

function createReader(file, whenReady) {
    reader.onload = function(evt) {
        var image = new Image();
        image.onload = function(evt) {
            var width = this.width;
            var height = this.height;
            if (whenReady) whenReady(width, height);
        };
        image.src = evt.target.result; 
    };
    reader.readAsDataURL(file);
}

Now when you call it, you can pass in a function to do whatever it is you want done with the image dimensions:

  createReader(input.files[i], function(w, h) {
    alert("Hi the width is " + w + " and the height is " + h);
  });

这篇关于HTML5 - 如何获取图片尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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