简体   繁体   中英

change src of img tag with input file

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.

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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM