change src of img tag with input file

user4014811

I have a input and img tag like this in my HTML code:

<input type="file" name="img2" id="chooseimg" onchange="readURL(this);">

<img id="img-edt" src="l1.png" alt="your image" width="502" height="319"/>

And in js i use this code to change image:

function readURL(input) {
 if (input.files && input.files[0]) {
     var reader = new FileReader();
     reader.onload = function(e) {
         $('#img-edt')
             .attr('src', e.target.result)
             .width(502)
             .height(319);
     };
     reader.readAsDataURL(input.files[0]);
 }
 showDimension();
 }

After that image load,i need to know the dimension of original image,so i use this function:

function showDimension() {
 var mm = document.getElementById("img-edt");
 var ww = mm.naturalWidth;
 var hh = mm.naturalHeight;
 var x = document.getElementById("teeest");
 x.innerHTML = "w is: " + String(ww) + "h is: " + String(hh);
 }

But the problem is that always it returns size of previous image. please help me with this problem.

dfsq

Since changing an image is an asynchronous operation, you have to move showDimension() function into onload callback as well:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#img-edt')
                .attr('src', e.target.result)
                .width(502)
                .height(319);
            showDimension();
        };
        reader.readAsDataURL(input.files[0]);
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related