[Clique aqui para ler em português]
Let’s create a tool with JavaScript that converts image to base64 and does the opposite, transforming base64 into an image.
Code
First we will create the interface, we will do something simple, using only HTML.
<input type="file"><br>
<textarea></textarea>
<img width="100" alt="Prévia da imagem...">
<button type="button">Download</button>
Here we have a file type input, we will receive the image upload, we also have a textarea that will be where the base64 image will be, we also have an img tag where the image preview will be and finally a download button to download the image.
Now let’s start the JavaScript part.
document.getElementsByTagName("input")[0].addEventListener("change", previewFile);
document.getElementsByTagName("textarea")[0].addEventListener("input", previewText);
document.getElementsByTagName("button")[0].addEventListener("click", downloadFile);
let preview = document.querySelector('img');
function previewFile(event) {
let reader = new FileReader();
let file = event.target.files[0];
reader.readAsDataURL(file);
reader.onloadend = () => {
preview.src = reader.result;
document.getElementsByTagName("textarea")[0].value = reader.result;
};
}
First we have the addition of events for the input
, textarea
and button
, then we have a preview
variable and finally we have the previewFile
function, in this function we use the FileReader
to help us work with the image loading, after the image has been loaded (onloadend
) added in the preview and the base64 code added in the textarea
.
function previewText(event) {
let file = event.target.value.replace(/^data:image\/[a-z]+;base64,/, "");
preview.src = `data:image/png;base64,${file}`;
}
function downloadFile() {
let nameFile = "Image.png";
var a = document.createElement("a");
a.href = preview.src;
a.download = nameFile;
a.click();
}
We now have two more functions:
-
previewText = Here we take the text received in the
textarea
and add thepreview
, thus convertingbase64
to image. -
DownloadFile = Here we download the image that is appearing in the
preview
.
ready as simple as that.
Demo
See the complete project working below.
Youtube
If you prefer to watch, I see the development on youtube (video in PT-BR).
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you! 😊😊
Top comments (0)