js base64 and canvas base64

Keywords: Javascript encoding

1, js base64

Get the uploaded file myfile, create a fileRead file object, and use the readAsDataURL method to encode the read file into a Data URL. After the file is loaded successfully, e.target.result is the base64 encoding corresponding to the file image. The image can be displayed by assigning the src of img directly.

<body>
        <input type="file" name="myfile" id="myfile" value="" onchange="sub()"/>
</body>
<script type="text/javascript">
   function sub(){
       var myfile = document.getElementById("myfile").files[0];
       var fileRead = new FileReader();
       fileRead.readAsDataURL(myfile);
        fileRead.onload = function(e){
                console.log(e);
                var base64 = e.target.result;
                console.log(base64);
                var img = new Image();
                img.src = base64;
                document.getElementsByTagName("body")[0].appendChild(img);
            }
   }
<script>

The following is the result of e object printing in onload. You can see that e.target.result is the information of the file image.


Print map

The code of base64 is printed below, which can be directly referenced in the src of img, or copied to the browser search box to search for pictures directly.


base64

The operation result is as follows:
B70AB62F-9251-4C48-BCB9-364E7A8B18F6.png

2, canvas base64

Use canvas to draw a rectangle filled with red. After the pilot button, use the canvas.toDataURL method: return a data URI containing the image display. You can use the type parameter, which defaults to PNG format. Assign the base64 code to img's src to display the image.

<body>
        <canvas id="mycanvas" width="500" height="500"></canvas>
        <button onclick="sub()">click</button>
</body>
<script type="text/javascript">
        var canvas = document.getElementById("mycanvas");
        var context = canvas.getContext("2d");
        context.beginPath();
        context.fillStyle = "red";
        context.fillRect(100,100,100,100);
        function sub(){
            var base64 = canvas.toDataURL();
            console.log(base64);
            var img = new Image();
            img.src = base64;
            document.getElementsByTagName("body")[0].appendChild(img);
        }
</script>

The results are as follows:


1BB0DDD2A17D8A72EC3FF604E221FF48.png

The base64 method of two kinds of pictures is very practical, which may be encountered in the project development. Let's share it with you today.

Posted by hardius on Fri, 01 May 2020 14:42:21 -0700