如何使用 JavaScript 将图像转换为 Base64 字符串

JavaScript 中有多种方法可以将图像转换为 Base64 字符串。

来自本地文件系统的图片

如果你需要从用户的文件系统转换图像,你应该使用 FileReader API:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <input type="file" onchange="encodeImageFileAsURL(this)" />
    <script>
      function encodeImageFileAsURL(element) {
        let file = element.files[0];
        let reader = new FileReader();
        reader.onloadend = function() {
          console.log('RESULT: ', reader.result);
        }
        reader.readAsDataURL(file);
      }
    </script>
  </body>
</html>

FileReader 对象允许 Web 应用异步读取存储在用户计算机上的文件的内容,使用 File 或者 Blob 对象指定要读取的文件或者数据。

FileReader

首先,通过 XMLHttpRequest 将图像加载为 blob,并使用 FileReader API 将其转换为 dataURL:

function toDataURL(url, callback) {
  let xhRequest = new XMLHttpRequest();
  xhRequest.onload = function () {
    let reader = new FileReader();
    reader.onloadend = function () {
      callback(reader.result);
    }
    reader.readAsDataURL(xhRequest.response);
  };
  xhRequest.open('GET', url);
  xhRequest.responseType = 'blob';
  xhRequest.send();
}
toDataURL('https://www.onitroad.com/avatar.png', function (dataUrl) {
  console.log('RESULT:', dataUrl)
})

这种方法具有更好的压缩效果,也适用于其他文件类型。

Canvas

首先,创建一个画布,然后将图像加载到其中并使用 toDataURL() 获取 Base64 表示。

其实它是一个数据URL,但它包含了Base64编码的图像:

function toDataURL(src, callback, outputFormat) {
  let image = new Image();
  image.crossOroirn = 'Anonymous';
  image.onload = function () {
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    let dataURL;
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  image.src = src;
  if (image.complete || image.complete === undefined) {
    image.src = "data:image/gif;base64, R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    image.src = src;
  }
}
toDataURL('https://www.onitroad.com/avatar.png',
  function (dataUrl) {
    console.log('RESULT:', dataUrl)
  }
)

这仅在我们不需要原始 Base64 字符串或者原始图像类型时才有用。
请注意,根据浏览器和操作系统的不同,此方法可能会为同一图像返回不同的结果。
它不仅会返回不同的 Base64 值,还会返回不同的图像。

日期:2020-06-02 22:16:13 来源:oir作者:oir