Simple Image into Base64 tool source address

So let’s cut to the code.

In my work, I found that previous people had done image conversion of BASE64 HTML file, but there was no preview, sometimes I do not know the image I transformed, so I wrote a later use in the work.

rendering

HTML

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Base64</title> <script SRC ="./ imagetobase64.js "></script> <link rel="stylesheet" Href ="./ imageTobase64.css "> </head> <body> <div> <div> <img id="img" --> <div> <input id="clickFile" type="file" onchange="preImageFile()"> SRC = "" height =" 300 "Alt =" pictures show preview area "> < / div > < div > conversion results look at the console < / div > < / body > < / HTML >Copy the code

FileReader knowledge point address

JS

function preImageFile() {
    const preImage = document.getElementById("img");  
    const file = document.getElementById("clickFile").files[0];
    // Allows Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer
    const reader = new FileReader();
    // Check whether the file is selected
    if(file){
        // Starts reading the contents of the specified Blob. Once complete, the Result property contains a Base64 string in data: URL format to represent the contents of the file being read.
        reader.readAsDataURL(file);
        // Handle the Load (en-us) event. This event is emitted when the read operation is complete.
        reader.onloadend =  () = >
        {
            // Preview the page to display the image
            preImage.src = reader.result;
            // The console outputs the result
            console.log(reader.result); }}else{
        preImage.src = ""; }}Copy the code

CSS

div {
    margin: 20px 20px;
}
Copy the code