get uploaded image dimensions with javascript / jquery?
-
18-09-2019 - |
Question
also try this but for me it isnt working.
Determining image file size + dimensions via Javascript?
i upload image, insert it on page through jquery and want to create div around inserted image, but dont know image dimensions.
$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
var img = document.getElementById('temp_image');
alert(img.clientWidth);
it show me 0, what is wrong ?
also tried:
var oImg = new Image();
oImg.src = 'uploads/obr1.jpg;
if (oImg.complete) {
alert(oImg.width)
}
it shows me 0 too.
where is problem ? thanks
Solution
Should be:
$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
var img = document.getElementById('tmp');
alert(img.clientWidth);
You are currently trying to get the width of the containing div (#temp_image), not the image.
Also, if you are using jQuery, you can just do:
$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
alert($('#tmp').width());
Hope this helps!
OTHER TIPS
var img = document.getElementById('temp_image');
doesn't actually get you the image element, it gets the element containing the image. You should try
var img = document.getElementById('tmp');
or
var img = $('#tmp')[0];
instead. Also make sure that the image is actually visible when you're getting it's dimensions, as clientWidth
and clientHeight
will be zero if the element is hidden.
I tried your method and it's working. You just didn't wrote it well. You forgot to close quotes.
var oImg = new Image();
oImg.src = 'uploads/obr1.jpg';
if (oImg.complete) {
alert(oImg.width)
}