Get full size of image in javascript/jquery

后端 未结 4 1750
甜味超标
甜味超标 2021-02-15 02:53

I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to

相关标签:
4条回答
  • 2021-02-15 03:10

    You can do this with an Image object that holds the same source file like:

    var preloader = new Image();
    preloader.src = 'path/to/my/file.jpg';
    
    preloader.onload = function(){
    var height = preloader.height;
    var width = preloader.width;
    }
    
    0 讨论(0)
  • 2021-02-15 03:16

    You can clone the image, remove the height and width attributes, append it to the body and get the width and size before removing it.

    jsFiddle demo is here: http://jsfiddle.net/58dA2/

    Code is:

    $(function() {
       var img = $('#kitteh'); // image selector
       var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
        $('#height').text(hiddenImg.height());
        $('#width').text(hiddenImg.width());
        hiddenImg.remove();            
    });​
    
    0 讨论(0)
  • 2021-02-15 03:24

    Images have naturalWidth and naturalHeight properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.

    One would still have to wait for the image to load though

    $('#idOfMyimg').on('load', function() {
        var height = this.naturalHeight,
            width  = this.naturalWidth;
    });
    

    Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it

    var img = new Image();
    
    img.onload = function() {
       var height = this.height,
           width  = this.width;
    }
    img.src = $('#idOfMyimg').attr('src');
    

    FIDDLE

    0 讨论(0)
  • 2021-02-15 03:29

    Try this:

    var pic = $("img")

    // need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height");

    var pic_real_width = pic.width(); var pic_real_height = pic.height();

    0 讨论(0)
提交回复
热议问题