Get full size of image in javascript/jquery

2020-06-12 05:57发布

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 return the current size of the image.

4条回答
▲ chillily
2楼-- · 2020-06-12 06:30

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;
}
查看更多
我只想做你的唯一
3楼-- · 2020-06-12 06:32

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

查看更多
仙女界的扛把子
4楼-- · 2020-06-12 06:34

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();

查看更多
小情绪 Triste *
5楼-- · 2020-06-12 06:37

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();            
});​
查看更多
登录 后发表回答