3

Given a list of image paths how can I iterate through them and find the actual image dimensions? I assume I have to insert them into the DOM without width or height properties and do a .width and .height on them?

Jason
  • 11,435
  • 24
  • 77
  • 131

1 Answers1

4
var paths = ['/path/image.png', 'somewhere/page.jpg'];

$.each(paths, function(i, path) {
    var img = new Image();

    $(img).load(function() {

        var width = img.width,
            height = img.height;

        alert(width + ' × ' + height);

    });

    img.src = path;

});

See it on jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
  • I have a question about that code. Yes, it works, but how are the width and height extracted from the Image object before the img.src veriable is set? – Michael Feb 04 '11 at 17:23
  • 1
    @Michael - the width and height are extracted "after" the img.src is set. The block of code right before the line `img.src = path;` is just the binding of the event handler to the _load_ event. The event handler doesn't run until the _load_ event happens, which is afterward. – tamakisquare Nov 29 '11 at 22:16