javascript HTML5 - 如何获取图像尺寸
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5173796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 - how to get image dimension
提问by angry kiwi
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
参考: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 createReaderfunction. How can I do that?
我想从createReader函数外部访问值宽度和高度。我怎样才能做到这一点?
回答by Pointy
Change "createReader" so that you pass in a handler function to be called when the image is available:
更改“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);
}
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);
});

