是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。
function getNeturalHeightWidth(file) {
let h, w;
let reader = new FileReader();
reader.onload = () => {
let tmpImgNode = document.createElement("img");
tmpImgNode.onload = function() {
h = this.naturalHeight;
w = this.naturalWidth;
};
tmpImgNode.src = reader.result;
};
reader.readAsDataURL(file);
}
return h, w;
}
其他回答
我认为这可能对2019年使用JavaScript和/或TypeScript的人有所帮助。
我发现以下内容是不正确的,就像一些人认为的那样:
let img = new Image();
img.onload = function() {
console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";
这是正确的:
let img = new Image();
img.onload = function() {
console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";
结论:
在onload函数中使用img,而不是this。
jQuery的答案:
$height = $('#image_id').height();
$width = $('#image_id').width();
当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:
$(document).ready(function(){
var width = img.clientWidth;
var height = img.clientHeight;
});
这个答案正是我所寻找的(在jQuery):
var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。
function getNeturalHeightWidth(file) {
let h, w;
let reader = new FileReader();
reader.onload = () => {
let tmpImgNode = document.createElement("img");
tmpImgNode.onload = function() {
h = this.naturalHeight;
w = this.naturalWidth;
};
tmpImgNode.src = reader.result;
};
reader.readAsDataURL(file);
}
return h, w;
}
推荐文章
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?