In front-end development, we often need to convert Base64-encoded strings into images to display on the web page. This conversion can help us dynamically load images and display them on the page without server support. Next, this article will introduce how to use JavaScript to convert a Base64-encoded string into an image.
1. Principle of Base64 encoding
Base64 encoding is an encoding method that converts binary data into printable ASCII characters. It converts every three bytes into four characters and adds a "=" sign at the end (if needed).
For example, a 16-bit binary number 1111010100110000 can be converted into a Base64-encoded string "5q0=". The conversion process is as follows:
2. Convert Base64 encoding to images in JavaScript
In front-end development, we often use Ajax asynchronous requests to obtain Base64 encoded strings, and then convert them into images and displayed on the web page. Here are the steps on how to convert a Base64-encoded string into an image using JavaScript:
<img id="img" src="" alt="image">
let base64Img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxglj NBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; document.getElementById("img").src = base64Img;
let img = document.createElement("img"); img.src = "image.png"; img.onload = function() { let canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); let base64Img = canvas.toDataURL("image/png"); document.getElementById("img").src = base64Img; }
The above is the method to convert Base64 encoding into pictures. Through this method, we can easily display Base64 encoded images in web pages.
The above is the detailed content of Convert base64 to image javascript. For more information, please follow other related articles on the PHP Chinese website!