一、方案一


// 图片路径
    var img = "imgurl";

    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
        var dataURL = canvas.toDataURL("image/"+ext);
        return dataURL;
    }
    var image = new Image();
    image.src = img;
    console.log(getBase64Image(image));

二、方案二


1、步骤
获取图片二进制文件,将二进制文件转换成base64
2、例子
(1)通过axios获取图片二进制文件

const imgUrl = "网图url";

 axios({
   method: "get",
   url: imgUrl,
   responseType: "blob",
 }).then((res) => {
   console.log(res);
   blobToDataURL(res.data, console.log);
 });
(2)通过fileReader,将文件转成base64



function blobToDataURL(blob, callback) {
  let a = new FileReader();
  a.onload = function (e) {
    callback(e.target.result);
  };
  a.readAsDataURL(blob);
}

3.在线示例

codepen


您已经阅读00:00:00欢迎留言评论,喜欢的话就为作者点个赞或者赏颗糖吧! 分享