Convert image to Base64 using JavaScript

 Preface

In web development, we often need to convert images to Base64 format so that they can be used directly in HTML without relying on external resources. In this post, I will show you how to convert an image to Base64 format using JavaScript.

  FileReade method

        First, we need to create a FileReader object, which is an API in HTML5 for reading file contents. Then, we need to listen to the FileReader loadevent. When the image is loaded, this event will be triggered. In the callback function of this event, we can get the Base64 encoding of the image. 

code show as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image to Base64</title>
</head>
<body>
    <input type="file" id="inputImage" />
    <script>
        const inputImage = document.getElementById('inputImage');
        inputImage.addEventListener('change', function(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function(e) {
                const base64 = e.target.result;
                console.log(base64); // 输出图片的Base64编码
            };
            reader.readAsDataURL(file);
        });
    </script>
</body>
</html>

 canvas method

        We can use canvas.toDataURL, which will use JavaScript to get the base64 encoding of the image. Here are the steps:

  1. Use JavaScript to create a reference to the canvas element.
  2. Use JavaScript to create a new Image object and set its source to the URL of the image you want to convert.
  3. When the image is loaded, draw it onto the canvas.
  4. Use the toDataURL method to convert the contents of the canvas into a base64-encoded string.
创建新的Image对象
var img = new Image();
img.src = 'your_image_url'; // 替换为你的图片URL
// 图片加载完成后,将其绘制到canvas上
img.onload = function() {
    getBase64(img);
};

/**图片转base64格式 */
export function getBase64(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    // 将canvas的内容转换为base64编码的字符串
    var base64 = canvas.toDataURL("image/png");// 可以根据需要更改为其他格式,如'image/jpeg'等
    return base64;
}

Guess you like

Origin blog.csdn.net/olderandyanger/article/details/122893574