Get image in jQuery

I want to get the image in jquery, I have this code. He works up to level

alert (v);

Interestingly, what’s wrong with the rest when v really 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

+3
source share
4 answers

Your code will not always work to get the image size. The image is loaded asynchronously, so the height and width will not be available immediately. You will need 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;
+4
source

Assuming #xxx is your input container identifier, 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>
0
source

URL- ?

, :

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

At the moment, you select input elements inside the element with the identifier "xxx", but you want the element to have the identifier "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);
0
source

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 assignment srcto end.

0
source

Source: https://habr.com/ru/post/1743141/


All Articles