views:

74

answers:

4

Hello,

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

A: 

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
#xxx is the input field, the value is passed to var v and alerted too
Jean
sorry, it works on FF but not Chrome
Puaka
checkout the updated script, should work on chrome, need to add delay, change it as you wish
Puaka
A: 

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
I got the correct value for V and there is only one input field
Jean
A: 

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
10 mins to load
Jean
10 minutes to load an image? How big an image are we talking here? Or is it down to your connection speed?
richsage
+4  A: 

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