jQuery/javascript - Get Image size before load

前端 未结 1 483
面向向阳花
面向向阳花 2021-01-13 07:39

I have a list of images that is rendered as thumbnails after upload. The issue that I have is I need the dimensions of the fully uploaded images, so that I can run a resize

相关标签:
1条回答
  • 2021-01-13 08:13

    There's a newer js method called naturalHeight or naturalWidth that will return the information you're looking for. Unfortunately it wont work in older IE versions. Here's a function I created a few months back that may work for you. I added a bit of your code below it for an example:

    function getNatural($mainImage) {
        var mainImage = $mainImage[0],
            d = {};
    
        if (mainImage.naturalWidth === undefined) {
            var i = new Image();
            i.src = mainImage.src;
            d.oWidth = i.width;
            d.oHeight = i.height;
        } else {
            d.oWidth = mainImage.naturalWidth;
            d.oHeight = mainImage.naturalHeight;
        }
        return d;
    }
    
    var img = $("#703504");
    var naturalDimension = getNatural(img);
    alert(naturalDimension.oWidth, naturalDimension.oHeight)​
    
    0 讨论(0)
提交回复
热议问题