线上图片转成 base64

body

          

js

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 dataURL = canvas.toDataURL("image/png");  // 可选其他值 image/jpeg
          return dataURL;
      }

      function main(src, cb) {
          var image = new Image();
          image.src = src + '?v=' + Math.random(); // 处理缓存
          image.crossOrigin = "*";  // 支持跨域图片
          image.onload = function(){
              var base64 = getBase64Image(image);
              cb && cb(base64);
          }
      }

      main('https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=151472226,3497652000&fm=26&gp=0.jpg', function(base64){
          console.log(base64);
      });

你可能感兴趣的:(线上图片转成 base64)