4

I want to read out the width (orgWidth) of an image specified by an url within a for-loop, calculate its new width (calcWidth) for a height of 480px.

for (var i=1; i <= item.length; i++) {

    url = document.images[i].rsc;
    orgWidth = some-fancy-thing-that-reads-the-width;
    orgHeight = some-fancy-thing-that-reads-the-height;

    factor = orgHeight / 480        // 1400 / 480 = 2.916
    calcWidth = orgWidth / factor       // 1000 / 2.916 = 342.935

    document.images[i].width = calcWidth;

}

Page I need it for: http://foto.hendrik-schicke.de/index.php/people

Kibou
  • 63
  • 1
  • 2
  • 8

3 Answers3

11
var tmpImg = new Image();
tmpImg.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png"; //or  document.images[i].src;
$(tmpImg).on('load',function(){
  var orgWidth = tmpImg.width;
  var orgHeight = tmpImg.height;
  alert(orgWidth+"x"+orgHeight);
});

Demo: http://jsfiddle.net/eWzWg/3/

Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
4

This is not possible using javascript, it is certainly not possible by 'not-preloading' either, as you would need to 'have' the file in order to do something with it.

Your best approach would be to hand off the URL of the image to a server side script (PHP?) that would get the image dimensions and pass the data back to you or store it in a DB (possibilities are endless here).

But to answer your question, it is not possible with pure javascript WITHOUT loading the image.

Jakub
  • 20,418
  • 8
  • 65
  • 92
4

We can check whether image is already loaded to browser's cache. Only if image is loaded, we bind onload handler to it. This is pure javascript example.

var image;
function onload () {
    console.log(image.height, image.width);
}

image= new Image();
image.src="https://www.google.com/intl/en_com/images/srpr/logo3w.png";
// check if image is already loaded to cache
if (image.complete) {
    console.log('image already loaded to browser');
    onload();
} else {
    // or bind onload handler for image
    image.onload = onload;
}

Play with that example at jsFiddle

aliaksej
  • 246
  • 2
  • 6