Bin Chen
Bin Chen

Reputation: 63309

How to get the downloaded image's width&height?

I want to set the width and height of the container <div> of <img> after the image is downloaded, how to do it?

Upvotes: 0

Views: 69

Answers (3)

Mike
Mike

Reputation: 2587

It is best to wait for the image to be loaded unless you want false results.

jQuery('#image').load(function() {
   var jThis = jQuery(this);
   var width = jThis.width();
   var height = jThis.height();
   yourFunction(width, height); //whatever you want to do with these values
   jThis.unbind('load'); //might be necessary if you only want this to happen once. Remove this if #image is a container for multiple uses.
})  

EDIT 1

Instead of yourFunction(), you could use this since it fits your description better:

jThis.parents('#container').css({
   width: width,
   height: height
});

Upvotes: 0

anton_byrna
anton_byrna

Reputation: 2555

function fn (div, url_path) {
  var img = new Image();

  img.onload = function () {
    div.style.width = img.width;
    div.style.height = img.height;
  };

  img.src = "url_path";
}

fn(document.getElementsByTagName('div')[0], 'http://some-url-to-image.com/1.jpg');

Upvotes: 1

Neil
Neil

Reputation: 5780

Put it on the page hidden, then measure its width. See here for a good explanation of how to measure the width of a hidden object (just calling width() returns 0).

Upvotes: 1

Related Questions