How to get image size (height & width) using JavaS

2018-12-31 00:59发布

Are there any jQuery or pure JS APIs or methods to get the dimensions of an image on the page?

23条回答
裙下三千臣
2楼-- · 2018-12-31 01:11
function outmeInside() {
var output = document.getElementById('preview_product_image');

 if (this.height < 600 || this.width < 600) {
     output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
     alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
 } else {
     output.src = URL.createObjectURL(event.target.files[0]);

 }
 return;

 }

 img.src = URL.createObjectURL(event.target.files[0]);
}

this work for multiple image preview and upload . if you have to select for each of the images one by one . Then copy and past into all the preview image function and validate!!!

查看更多
牵手、夕阳
3楼-- · 2018-12-31 01:12

Before using real image size you should load source image. If you use JQuery framework you can get real image size in simple way.

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})
查看更多
大哥的爱人
4楼-- · 2018-12-31 01:13

You can programmatically get the image and check the dimensions using Javascript...

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

This can be useful if the image is not a part of the markup.

查看更多
情到深处是孤独
5楼-- · 2018-12-31 01:13

You can also use:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 01:14

This answer was exactly what I was looking for (in jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
查看更多
人气声优
7楼-- · 2018-12-31 01:15

If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});
查看更多
登录 后发表回答