4

I have several images in an HTML document. The width of those elements is often modified due to a max-width CSS property that is applied to all of them.

I want to know whether it is possible to get both the real width of the .jpeg/.png/.whatever image files and the width that is being shown to the user, this is, I want to be able to know whether the images are being resized due to the max-width property or not.

Resizing the images with JavaScript after the page has loaded instead of using max-width is not acceptable.

dzz
  • 327
  • 3
  • 12

2 Answers2

0

The answer (pointed by someone who just deleted it) is to use naturalWidth.

dzz
  • 327
  • 3
  • 12
  • FYI, naturalWidth/Height aren't implemented in IE<9 to the best of my knowledge. It's safer (for now) to measure the image off-page -- or at least as a fallback mechanism. – svidgen May 15 '13 at 20:08
  • @svidgen I have one question: Why IE doesn't automatically update to latest version? Or why do ever people use lower version of any browser than the latest? This is one thing I can't ever understand. – Ms. Nobody May 16 '13 at 08:42
  • @Ms.Nobody As someone who once tried to do frantic weekend debugging of an automatic Chrome update that made everyone everywhere unable to use our product because of a randomly-introduced Flash incompatibility/security dialog, I can assure you; there are legitimate reasons. – Katana314 Oct 08 '14 at 20:16
0

window.addEventListener("load", function() {
  var imgs = document.querySelectorAll('img');
  for (var i = 0; i < imgs.length; i++) {
    var imgTag = imgs[i];
    var image = new Image();
    image.src = imgTag.src;
    output.innerHTML = "Width: " + image.width + " Height: " + image.height;
  }
});
img {
  max-width: 200px;
}
<img src="http://www.google.com/images/srpr/logo11w.png"/>
<p id="output"></p>

I just put this together, and it seemed to work.

It depends on the JavaScript Image type. I also used "onload" rather than DOMContentLoaded, so that when querying about the image, we can be certain that it's already been loaded and doesn't need to wait for its onLoad callback.

Katana314
  • 8,429
  • 2
  • 28
  • 36