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

后端 未结 30 2228
傲寒
傲寒 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:40

    I use different approach, simply make Ajax call to server to get image size when image object is in use.

    //make json call to server to get image size
    $.getJSON("http://server/getimagesize.php",
    {"src":url},
    SetImageWidth
    );
    
    //callback function
    function SetImageWidth(data) {
    
        var wrap = $("div#image_gallery #image_wrap");
    
        //remove height
         wrap.find("img").removeAttr('height');
        //remove height
         wrap.find("img").removeAttr('width');
    
        //set image width
        if (data.width > 635) {
            wrap.find("img").width(635);
        }
        else {
             wrap.find("img").width(data.width);
        }
    }
    

    and of course server side code:

    <?php
    
    $image_width = 0;
    $image_height = 0;
    
    if (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {
    
        $imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);
        if ($imageinfo) {
           $image_width=  $imageinfo[0];
           $image_height= $imageinfo[1];
        }
    }
    
    $arr = array ('width'=>$image_width,'height'=>$image_height);
    
    echo json_encode($arr);
    
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:42

    Use the naturalHeight and naturalWidth attributes from HTML5.

    For example:

    var h = document.querySelector('img').naturalHeight;
    

    Works in IE9+, Chrome, Firefox, Safari and Opera (stats).

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

    Another suggestion is to use imagesLoaded plugin.

    $("img").imagesLoaded(function(){
    alert( $(this).width() );
    alert( $(this).height() );
    });
    
    0 讨论(0)
  • 2020-11-22 01:44

    There's a lot of discussion in the accepted answer about a problem where the onload event doesn't fire if an image is loaded from the WebKit cache.

    In my case, onload fires for cached images, but the height and width are still 0. A simple setTimeout resolved the issue for me:

    $("img").one("load", function(){
        var img = this;
        setTimeout(function(){
            // do something based on img.width and/or img.height
        }, 0);
    });
    

    I can't speak as to why the onload event is firing even when the image is loaded from the cache (improvement of jQuery 1.4/1.5?) — but if you are still experiencing this problem, maybe a combination of my answer and the var src = img.src; img.src = ""; img.src = src; technique will work.

    (Note that for my purposes, I'm not concerned about pre-defined dimensions, either in the image's attributes or CSS styles — but you might want to remove those, as per Xavi's answer. Or clone the image.)

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

    This works for both cached and dynamically loaded images.

    function LoadImage(imgSrc, callback){
      var image = new Image();
      image.src = imgSrc;
      if (image.complete) {
        callback(image);
        image.onload=function(){};
      } else {
        image.onload = function() {
          callback(image);
          // clear onLoad, IE behaves erratically with animated gifs otherwise
          image.onload=function(){};
        }
        image.onerror = function() {
            alert("Could not load image.");
        }
      }
    }
    

    To use this script:

    function AlertImageSize(image) {
      alert("Image size: " + image.width + "x" + image.height);
    }
    LoadImage("http://example.org/image.png", AlertImageSize);
    

    Demo: http://jsfiddle.net/9543z/2/

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

    As Luke Smith says, image load is a mess. It's not reliable on all browsers. This fact has given me great pain. A cached image will not fire the event at all in some browsers, so those who said "image load is better than setTimeout" are wrong.

    Luke Smith's solution is here.

    And there is an interesting discussion about how this mess might be handled in jQuery 1.4.

    I have found that it's pretty reliable to set the width to 0, then wait for the "complete" property to go true and the width property to come in greater than zero. You should watch for errors, too.

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