Get the real width and height of an image with JavaScript? (in Safari/Chrome)

后端 未结 30 2230
傲寒
傲寒 2020-11-22 01:16

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

相关标签:
30条回答
  • 2020-11-22 01:30

    You can programmatically get the image and check the dimensions using Javascript without having to mess with the DOM at all.

    var img = new Image();
    img.onload = function() {
      console.log(this.width + 'x' + this.height);
    }
    img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
    
    0 讨论(0)
  • 2020-11-22 01:31

    
    function getOriginalWidthOfImg(img_element) {
        var t = new Image();
        t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
        return t.width;
    }
    

    You don't need to remove style from the image or image dimensions attributes. Just create an element with javascript and get the created object width.

    0 讨论(0)
  • 2020-11-22 01:32

    This works cross browser

    var img = new Image();
    $(img).bind('load error', function(e)
    {
        $.data(img, 'dimensions', { 'width': img.width, 'height': img.height });                    
    });
    img.src = imgs[i];              
    

    get the dimensions by using

    $(this).data('dimensions').width;
    $(this).data('dimensions').height;
    

    Cheers!

    0 讨论(0)
  • 2020-11-22 01:33

    As stated before, Xavi answer won't work if images are in the cache. The issue responds to webkit not firing the load event on cached images, so if the width/height attrs are no explicitly set in the img tag, the only reliable way to get the images is to wait for the window.load event to be fired.

    The window.load event will fire always, so it's safe to access the width/height of and img after that without any trick.

    $(window).load(function(){
    
       //these all work
    
       $('img#someId').css('width');
       $('img#someId').width();
       $('img#someId').get(0).style.width;
       $('img#someId').get(0).width; 
    
    });
    

    If you need to get the size of dynamically loaded images that might get cached (previously loaded), you can use Xavi method plus a query string to trigger a cache refresh. The downside is that it will cause another request to the server, for an img that is already cached and should be already available. Stupid Webkit.

    var pic_real_width   = 0,
        img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();
    
    $('<img/>').attr('src', img_src_no_cache).load(function(){
    
       pic_real_width = this.width;
    
    });
    

    ps: if you have a QueryString in the img.src already, you will have to parse it and add the extra param to clear the cache.

    0 讨论(0)
  • 2020-11-22 01:33

    Check out this repository in github!

    Great Example to check the Width and Height using Javascript

    https://github.com/AzizAK/ImageRealSize

    ---Edited is requested from some comments ..

    Javascript code:

     function CheckImageSize(){
    var image = document.getElementById("Image").files[0];
               createReader(image, function (w, h) {
    
                    alert("Width is: " + w + " And Height is: "+h);
    });            
    }
    
    
      function  createReader(file, whenReady) {
            var reader = new FileReader;
            reader.onload = function (evt) {
                var image = new Image();
                image.onload = function (evt) {
                    var width = this.width;
                    var height = this.height;
                    if (whenReady) whenReady(width, height);
                };
                image.src = evt.target.result;
            };
            reader.readAsDataURL(file);
        }
    

    and HTML code :

    <html>
    <head>
    <title>Image Real Size</title>
    <script src="ImageSize.js"></script>
    </head>
    <body>
    <input type="file" id="Image"/>
    <input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
    </body>
    <html>
    
    0 讨论(0)
  • 2020-11-22 01:35

    How we get right real dimensions without a blink real image:

    (function( $ ){
       $.fn.getDimensions=function(){
             alert("First example:This works only for HTML code without CSS width/height definition.");
             w=$(this, 'img')[0].width;
             h=$(this, 'img')[0].height;
    
             alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
    
             //This is bad practice - it shows on your monitor
             $(this, 'img')[0].removeAttribute( "width" );
             $(this, 'img')[0].removeAttribute( "height" );
             alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+  $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
             //I'am going to repare it
             $(this, 'img')[0].width=w;
             $(this, 'img')[0].height=h;
             //This is a good practice - it doesn't show on your monitor
             ku=$(this, 'img').clone(); //We will work with a clone
             ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
             ku[0].removeAttribute( "width" );
             ku[0].removeAttribute( "height" );
             //Now we still get 0
             alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
             //Hide a clone
             ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'}); 
             //A clone appending
             $(document.body).append (ku[0]);
             alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
             //Remove a clone
             $("#mnbv1lk87jhy0utrd").remove();
    
             //But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
             alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
             imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object 
             imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
             imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy 
             $(document.body).append (imgcopy);//append to document 
             alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
             $("#mnbv1lk87jhy0aaa").remove();
    
    
       }
    })( jQuery );
    
    $(document).ready(function(){
    
       $("img.toreaddimensions").click(function(){$(this).getDimensions();});
    });
    

    It works with <img class="toreaddimensions"...

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