2

Looking for a way to get the dimensions (width and height) of an external image.
I have used prop() and attr(), but they don't return any values. Just an error.

Example:

<a href="pathtotheimage">some link</a>
Simon Arnold
  • 14,397
  • 6
  • 62
  • 81
user759235
  • 1,698
  • 3
  • 29
  • 55

3 Answers3

8

jQuery

var path = 'https://source.unsplash.com/random/600x300/?montreal';
$("<img/>").attr('src', path).load(function() {
    console.log(this.width, this.height);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Vanilla Javascript

var path = 'https://source.unsplash.com/random/600x300/?montreal';
var img = new Image();
img.src = path;
img.addEventListener('load', function() {
  console.log(this.width, this.height);
});
Simon Arnold
  • 14,397
  • 6
  • 62
  • 81
  • 1
    The `.load` event won't fire if the image is pulled from the browser cache. See [this question](http://stackoverflow.com/q/3877027/901048) for solutions. – Blazemonger Apr 26 '12 at 18:12
2

Looks like none has provided a working vanilla js answer.

var img = document.createElement('img')
img.src = 'http://domain.com/img.png'
img.onload = function() {
    console.log( this.width )
    console.log( this.height )
}

Here is a jsfiddle: http://jsfiddle.net/Ralt/VMfVZ/

Simon Arnold
  • 14,397
  • 6
  • 62
  • 81
Florian Margaine
  • 50,873
  • 14
  • 87
  • 110
-1

This isn't technically jQuery but I would go down the route of:

var image = new Image(), width, height;
image.src = 'http://whereyourimage.is/heresmyimage.jpg';
width = image.width;
height = image.height;

You can then access those values using width and height, for example alert('My image is ' + width + ' pixels accross.');

Tom Hallam
  • 1,848
  • 14
  • 23
  • 2
    This cannot work because you are accessing the width at the same time you are setting the src so the browser cannot possibly give you the correct information. – Esailija Apr 26 '12 at 17:55
  • Worked for me but I've just realised that image was cached! Fool! Will edit answer when I'm back at a computer – Tom Hallam Apr 26 '12 at 18:50