-3

What I am trying to do is put a specific sized 'div' around a image based on the image size. I have the images I am going to use in a array. I need to get the height and width of the image in the array. I must have the height and width before it is appended to the page.

var images = ['pic1.jpg','pic2.jpg','pic3.jpg'];

for(i = 0; i < images.length; i++){

                                   //then what do i do here? thanks for your help

}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • possible duplicate of [How to get image size (height & width) using JavaScript?](http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript) – FWDekker Jul 18 '15 at 23:38
  • Nope not a duplicate, the above is to get height and width of image once on the page.. i need the height and with before it is appended to the to the page – Dezmyn Beatty Jul 18 '15 at 23:41
  • Then it is a possible duplicate of this one: http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript – FWDekker Jul 18 '15 at 23:43
  • @DezmynBeatty You have to load it first, then you can determine its dimensions. http://jsfiddle.net/DerekL/paw9dusL/ – Derek 朕會功夫 Jul 18 '15 at 23:43

1 Answers1

2

You could, probably, do:

var img;
var images = ['pic1.jpg','pic2.jpg','pic3.jpg'];
var length = images.length;
var imagesSizes = [];
var loadedImages = 0;
for(i = 0; i < length; i++){
  img = new Image();
  img.addEventListener("load", function(){
    var height = this.height, width = this.width;
    loadedImages++;
    imagesSizes[i] = {
      height: height,
      width: width
    }
    if (loadedImages === length) {
      allImagesAreLoaded();
    }
  });
  img.src = images[i];
}
function allImagesAreLoaded() {
  console.log(imagesSizes); //You will have all their sizes here and each element will match the image index in the original array
}
Mindastic
  • 4,023
  • 3
  • 19
  • 20