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

前端我需要将我的图像转换为 Base64 字符串然后传送给后端,但是我怎么样才能把图片转换为 Base64 字符串?

function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}

toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})

参考这个博客文章,可以用js转图片为base64。
https://www.cnblogs.com/xielong/p/9643276.html


// 重写文件上传方法
    fileUpload(file) {
      this.fileToBase64(file.file)
        .then(res => {
          // console.log(res)
          this.imgSrc = res;
          this.dataForm.extName = res.substring(
            res.indexOf("/") + 1,
            res.indexOf(";")
          );
          const len = 19 + this.dataForm.extName.length;
          this.dataForm.fileBase64 = res.substring(len);
          // console.log(this.dataForm.fileBase64)
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err);
        });
    },
    // 转base64
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let fileResult = "";
        if (file.size > 1024 * 1024 * 4) {
          reject("文件大小不能超过4M");
        }
        reader.readAsDataURL(file);
        // 开始转
        reader.onload = () => {
          fileResult = reader.result;
          // data:image/jpeg;base64,
        };
        // 转 失败
        reader.onerror = function(error) {
          reject(error);
        };
        // 转 结束  咱就 resolve 出去
        reader.onloadend = function() {
          resolve(fileResult);
        };
      });
    }
  }