0

I tried to get the actual size of images before they are displayed on HTML, and I do use this in most cases:

var imgae = new Image();
image.src = img.src;
image.onload = function() {
    // Do something with image.width and image.height
    // and insert an <img> into <body>
}

However when the image is too large so that it may take seconds to download, users have to wait until it completes before seeing the image. Is there any way where I can get the information before Image.onload is triggered (and of cause after the meta data of image is loaded), so that I can show part of it on the page?

Benber Zhang
  • 71
  • 2
  • 5
  • @AlexD setInterval does work for me, though looks strange here. Thanks a lot. – Benber Zhang Aug 24 '16 at 10:33
  • this question is already answered here : http://stackoverflow.com/questions/6575159/get-image-dimensions-with-javascript-before-image-has-fully-loaded – Gajen Aug 24 '16 at 12:09

3 Answers3

0

If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

If you are using jQuery 3.0 remember that load method was removed, use $('img').on('load', function() {})

Coder
  • 240
  • 2
  • 4
  • 20
  • 1
    If you are using jQuery 3.0 remember that `load` method was removed, use `$('img').on('load', function() {})` instead. – ofca Aug 24 '16 at 10:26
0

You can make your function asynchronous with simply using an appropriate callback:

function loadImages(imgsrc, callback) {
    var image = new Image();
    image.onload = callback;
    image.src = imgsrc;
}

and then you can call this function easily like this

loadImages('you image src', function() {
    // whatever code to be executed
});

Hope if works for you.

Majid
  • 2,507
  • 2
  • 19
  • 18
0
  var _URL = window.URL || window.webkitURL;
  function displayPreview(files) {
    var file = files[0]
    var img = new Image();
    var sizeKB = file.size / 1024;
     img.onload = function() {
       $('#preview').append(img);
       alert("Size: " + sizeKB + "KB\nWidth: " + img.width + "\nHeight: " + img.height);
       }
       img.src = _URL.createObjectURL(file);
      }
satwick
  • 135
  • 9