How to get image size (height & width) using JavaScript?

前端 未结 29 3007
忘了有多久
忘了有多久 2020-11-21 05:23

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

相关标签:
29条回答
  • 2020-11-21 05:56

    Also (in addition to Rex and Ian's answers) there is:

    imageElement.naturalHeight
    

    and

    imageElement.naturalWidth
    

    These provide the height and width of the image file itself (rather than just the image element).

    0 讨论(0)
  • 2020-11-21 05:58

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

    const 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.

    0 讨论(0)
  • 2020-11-21 05:58

    clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

    var img = document.getElementById('imageid'); 
    //or however you get a handle to the IMG
    var width = img.clientWidth;
    var height = img.clientHeight;
    
    0 讨论(0)
  • 2020-11-21 05:58
    var imgSrc, imgW, imgH;
    function myFunction(image){
        var img = new Image();
        img.src = image;
        img.onload = function() {   
            return {
                src:image,
                width:this.width,
                height:this.height};
            }
        return img;
    }
    var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
        //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
    x.addEventListener('load',function(){
        imgSrc = x.src;
        imgW = x.width;
        imgH = x.height;
    });
    x.addEventListener('load',function(){
        console.log(imgW+'x'+imgH);//276x110
    });
    console.log(imgW);//undefined.
    console.log(imgH);//undefined.
    console.log(imgSrc);//undefined.
    

    This is my method, hope this helpful. :)

    0 讨论(0)
  • 2020-11-21 06:00

    Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.

    I found the following, as some have suggested, to be incorrect:

    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";
    

    This is correct:

    let img = new Image();
    img.onload = function() {
      console.log(img.width, img.height)
    };
    img.src = "http://example.com/myimage.jpg";
    

    Conclusion:

    Use img, not this, in onload function.

    0 讨论(0)
  • 2020-11-21 06:01

    Using JQuery you do this:

    var imgWidth = $("#imgIDWhatever").width();
    
    0 讨论(0)
提交回复
热议问题