HTML5 - 如何获取图像尺寸

ang*_*iwi 13 javascript 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]);
}
Run Code Online (Sandbox Code Playgroud)

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

Poi*_*nty 29

更改"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);
}
Run Code Online (Sandbox Code Playgroud)

现在,当你调用它时,你可以传递一个函数来做你想要的图像尺寸:

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

  • @kimsia以及许多类似的API都是“异步的”-当您调用它们时,一系列事件被设置为运动中,但并非所有事件都会立即发生。“回调”机制使您可以放置​​要在长期操作完成后运行的代码。网络操作,文件系统交互以及诸如此类的其他事情都是异步的,因为这些事情涉及的不是立即发生的硬件现实。 (2认同)