【问题标题】:HTML5 - how to get image dimensionHTML5 - 如何获取图像尺寸
【发布时间】:2011-07-07 14:59:27
【问题描述】:

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

参考: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 函数外部访问值的宽度和高度。我该怎么做?

【问题讨论】:

  • 嗯...让createReader返回一些东西。这是一个好的开始。
  • var width 和 height 只能在 image.onload 函数内部访问,这就是为什么我不能“返回一些东西”
  • 不能在要返回的范围内创建变量width和height,比如createReader函数吗?
  • @victor:你能解释更多或者举个例子吗?
  • @Victor 那行不通...

标签: javascript html


【解决方案1】:

更改“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);
  });

【讨论】:

  • 很棒的答案。如果我可以给 10 票,我会的! whenReady 真的帮助了我,因为我不知道为什么有时检索高度有效,有时却无效。关于何时使用 whenReady 类型处理程序的任何进一步说明。为什么使用 File API 读取文件需要它?
  • @kimsia 很多类似的 API 都是异步 - 当您调用它们时,会启动一系列事件,但不会立即发生。 “回调”机制让您可以放置​​在长期操作完成时运行的代码。网络操作、文件系统交互和其他类似的东西是异步的,因为这些东西涉及不是即时的硬件现实。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2011-09-21
  • 2015-10-24
  • 1970-01-01
  • 2011-04-22
  • 2021-10-18
相关资源
最近更新 更多