我有下面的angular-js指令来‘上传’本地图片:
app.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
//File URL to view
url: (URL || webkitURL).createObjectURL(item),
// File Input Value
_file: item
};
values.push(value);
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);我现在想要获取图像尺寸,但我不知道如何获取。我尝试了类似的方法(在values.push(Value)行下面):
var img = new Image();
img.src = value.url;
alert("Width: " + img.width);但这并不管用。我也尝试了img.onload,但是我也没有得到结果。
如何获取图像尺寸?
谢谢!
发布于 2016-08-02 22:22:16
我自己解决了这个问题,image.onload是正确的选择:
app.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var img = new Image();
var imgheight = 0;
var imgwidth = 0;
var imgurl = (URL || webkitURL).createObjectURL(item);
img.src = imgurl;
img.onload = function() {
imgheight = img.height;
imgwidth = img.width;
//alert("Width: " + imgheight + " height: " + imgwidth);
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
//File URL to view
url: imgurl,
// File Input Value
_file: item,
width: imgwidth,
height: imgheight,
mystyle: {}
};
scope.$apply(function () {
values.push(value);
});
};
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);https://stackoverflow.com/questions/38716912
复制相似问题