我有这个脚本,它用于获取浏览器上传图像的宽度和高度.
参考: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)