3

I want to get the imagesize in jquery, I have this code. It works to the point of

alert (v);

I wonder what is wrong with the rest when v actually contains a value.

 var v = $('#xxx input').val();
    alert (v);
    var newImg = new Image();
    newImg.src = v;
    var height = newImg.height;
    var width = newImg.width;
    alert ('The image size is '+width+'*'+height);

Thanks Jean

X10nD
  • 21,638
  • 45
  • 111
  • 152

4 Answers4

4

Your code to get the image size won't always work. The image loads asynchronously, so the height and width will not be available immediately. You'll need something like the following:

var newImg = new Image();
var height, width;

newImg.onload = function() {
    height = newImg.height;
    width = newImg.width;
    window.alert('The image size is '+width+'*'+height);
};

newImg.src = v;
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

assuming that #xxx is your input container id, your code should work :

<div id="xxx" align="center">
    <input name="test" value="/images/image1.jpg" />
</div>

Update For Chrome

<script type="text/javascript">
    var newImg = new Image();
    $(function() {
        var v = $('#xxx input').val();
        alert(v);
        newImg.src = v;
        setTimeout(function() {
            var height = newImg.height;
            var width = newImg.width;
            alert ('The image size is '+width+'*'+height);
        }, 1000);
    });
</script>
Puaka
  • 1,751
  • 13
  • 8
0

Are you receiving the correct URL to the image when you alert it?

My first idea would be to change the first line to:

var v = $('#xxx').val();

At the moment, you're selecting input elements inside an element with the ID of "xxx", but you want the element that has the ID "xxx".

Edit: another idea:

var v = $('#xxx input').val();
document.body.appendChild((function() {
    var newImg = document.createElement("img");
    newImg.src = v;
    newImg.id = "newImg";
    return newImg;
})());

var height = $("#newImg").attr("height");
var width = $("#newImg").attr("width");
alert('The image size is '+width+'*'+height);
GlenCrawford
  • 3,359
  • 3
  • 26
  • 34
0

You need to wait for the image to load!

var v = $('#xxx input').val();
alert (v);
var newImg = new Image();
newImg.onload = function() {
  var height = this.height;
  var width = this.width;
  alert ('The image size is '+width+'*'+height);
}
newImg.src = v;

EDIT: Moved the src assignment to the end.

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • 10 minutes to load an image? How big an image are we talking here? Or is it down to your connection speed? – richsage Apr 28 '10 at 09:58