<input type="file" id="picture">
I would like to convert the image uploaded to the html input to a string. How can I do that using JavaScript?
Thanks in advance.
<input type="file" id="picture">
I would like to convert the image uploaded to the html input to a string. How can I do that using JavaScript?
Thanks in advance.
Having
<input type="file" id="picture">
You can add an event handler to it listening to the change event (this code has to come after the above HTML or be registered on the DOMContentLoaded
event)
var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);
Then your handleFiles
event would draw the image into a canvas and extract the base64 string from the file:
function handleFiles(e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var base64 = canvas.toDataURL();
console.log(base64);
}
img.src = URL.createObjectURL(e.target.files[0]);
}
Running example bellow:
var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);
function handleFiles(e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var base64 = canvas.toDataURL();
document.getElementById('result').value = base64;
}
img.src = URL.createObjectURL(e.target.files[0]);
}
textarea {
width: 350px;
height: 100px;
}
<input type="file" id="picture" />
<br /> <br />
<textarea id="result"></textarea>
If what you want is a dataURI version, use a FileReader
and its readAsDataURL()
method.
file_input.onchange = function(e) {
var fr = new FileReader();
fr.onload = function() {
output.src = this.result;
}
fr.readAsDataURL(this.files[0]);
};
<input type="file" id="file_input" />
<img id="output" />
If you just want to display it, then you can use the URL Constructor :
file_input.onchange = function(e) {
output.src = URL.createObjectURL(this.files[0]);
};
// don't forget to revoke the URLObject when you don't need it anymore
output.onload = function() {
URL.revokeObjectURL(this.src);
}
<input type="file" id="file_input" />
<img id="output" />