美文网首页
js将远程url图片转base64

js将远程url图片转base64

作者: Frank_Fang | 来源:发表于2020-12-21 13:52 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    
    <body>
      <img id="img" src="" width="200" height="200" />
    
      <script>
        var img = "https://img.yzcdn.cn/vant/cat.jpeg";
        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.crossOrigin = '';
        image.src = img;
        image.onload = function () {
          var base64 = getBase64Image(image);
          console.log(base64);
          document.getElementById('img').src = base64
        }
    
      </script>
    </body>
    
    </html>

    相关文章

      网友评论

          本文标题:js将远程url图片转base64

          本文链接:https://www.haomeiwen.com/subject/yxurnktx.html