[removed] Get image dimensions

后端 未结 8 1777
攒了一身酷
攒了一身酷 2020-11-29 19:11

I only have a URL to an image. I need to determine the height and width of this image using only JavaScript. The image cannot be visible to the user on the page. How can I g

8条回答
  •  攒了一身酷
    2020-11-29 19:51

    Get image size with jQuery

    function getMeta(url){
        $("",{
            load : function(){
                alert(this.width+' '+this.height);
            },
            src  : url
        });
    }
    

    Get image size with JavaScript

    function getMeta(url){   
        var img = new Image();
        img.onload = function(){
            alert( this.width+' '+ this.height );
        };
        img.src = url;
    }
    

    Get image size with JavaScript (modern browsers, IE9+ )

    function getMeta(url){   
        var img = new Image();
        img.addEventListener("load", function(){
            alert( this.naturalWidth +' '+ this.naturalHeight );
        });
        img.src = url;
    }
    

    Use the above simply as: getMeta( "http://example.com/img.jpg" );

    https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

提交回复
热议问题