Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the width of an image specified by an url jquery

Tags:

jquery

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

like image 490
Kibou Avatar asked Dec 03 '22 00:12

Kibou


2 Answers

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/

like image 189
Muhammad Usman Avatar answered Mar 03 '23 23:03

Muhammad Usman


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.

like image 41
Jakub Avatar answered Mar 03 '23 21:03

Jakub