2011-03-02 142 views
11

我有这个脚本,它用于获取浏览器上传图像的宽度和高度。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); // 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]); 
} 

我想从createReader函数外部访问该值宽度和高度。我怎样才能做到这一点?

+1

嗯...有'createReader'返回的东西。这是一个好的开始。 –

+0

var width和height只能访问image.onload函数内部,这就是为什么我不能“返回某些东西” –

+0

您不能在要返回它们的范围中创建变量'width'和'height' ,比如'createReader'函数? –

回答

26

改变“createReader”,让你在处理函数传递到被调用时,图像可用:

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); 
} 

现在,当你调用它,你可以传递一个函数做什么是你想要完成的图像尺寸:

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

梦幻般的答案。如果我可以给10个upvotes,我会! whenReady真的帮助了我,因为我不知道为什么有时候高度的检索有效,有时候并没有。有关何时使用whenReady类型处理程序的进一步解释。为什么使用File API读取文件需要它? –

+1

@ kimsia很多这样的API都是**异步** - 当你调用它们时,一系列事件被设置为运动,但它不会立即发生。 “回调”机制可以让您在长期操作完成时将代码运行。网络操作,文件系统交互以及其他类似的东西是异步的,因为这些东西涉及的硬件现实不是直接的。 – Pointy