我有这个脚本,它用于获取浏览器上传图像的宽度和高度。
参考: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
函数外部访问值的宽度和高度。我怎么能这样做?
答案 0 :(得分: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);
}
现在,当你调用它时,你可以传递一个函数,用图像尺寸做你想做的事情:
createReader(input.files[i], function(w, h) {
alert("Hi the width is " + w + " and the height is " + h);
});