Storing image (input file) in characters and restoring to file again (?)

Asked

Viewed 20 times

0

This code gets an image for input file and "transforms" into characters
There is a way to reverse the situation, with the characters obtained in the console.log forming the image again (throwing the image in the div secondImageView)?
Thank you and follow the code:

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
        console.log(oFREvent.target.result);
        document.getElementById("txtimg").value = oFREvent.target.result;
    };
};
<html>
  <body>
    <img id="uploadPreview" style="width: 200px; height: 100px; border: 1px #000 solid" />
    <input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" /> <br /> <br />
    <input id="txtimg" name="name_txt" class="txtimg" style="width:46px;" type="text"> <br>
    <img id="secondImageView" style="width: 200px; height: 100px; border: 1px #000 solid" />
  </body>
</html>

1 answer

1


It is possible yes, just change the attribute src tag <img> that you wish, follows example below.

Note: These characters are in Base64, which is an encoding used to transmit binary data by text.

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
        console.log(oFREvent.target.result);
        document.getElementById("txtimg").value = oFREvent.target.result;
        
        // Modificando o src da imagem
        document.getElementById('secondImageView').setAttribute('src', oFREvent.target.result);
    };
};
<html>
  <body>
    <img id="uploadPreview" style="width: 200px; height: 100px; border: 1px #000 solid" />
    <input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" /> <br /> <br />
    <input id="txtimg" name="name_txt" class="txtimg" style="width:46px;" type="text"> <br>
    <img id="secondImageView" style="width: 200px; height: 100px; border: 1px #000 solid" />
  </body>
</html>

  • Very obg @Dobrychtop, I’ll study the code, you’re absolutely right !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.