当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js 图片转base64的方式(两种)

js 图片转base64的方式(两种)

2018年04月25日  | 移动技术网IT编程  | 我要评论

方式一:blob和filereader 对象

实现原理:

使用xhr请求图片,并设置返回的文件类型为blob对象[xhr.responsetype = "blob"]

使用filereader 对象接收blob

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>js 图片转base64方式</title>
</head>
<body>
  <p id="container1"></p>
  <script>
    getbase64("https://z649319834.github.io/learn_example/video_track/webvtt.jpg")
    function getbase64(imgurl) {
      window.url = window.url || window.webkiturl;
      var xhr = new xmlhttprequest();
      xhr.open("get", imgurl, true);
      // 至关重要
      xhr.responsetype = "blob";
      xhr.onload = function () {
        if (this.status == 200) {
          //得到一个blob对象
          var blob = this.response;
          console.log("blob", blob)
          // 至关重要
          let ofilereader = new filereader();
          ofilereader.onloadend = function (e) {
            let base64 = e.target.result;
            console.log("方式一》》》》》》》》》", base64)
          };
          ofilereader.readasdataurl(blob);
          //====为了在页面显示图片,可以删除====
          var img = document.createelement("img");
          img.onload = function (e) {
            window.url.revokeobjecturl(img.src); // 清除释放
          };
          let src = window.url.createobjecturl(blob);
          img.src = src
          document.getelementbyid("container1").appendchild(img);
          //====为了在页面显示图片,可以删除====

        }
      }
      xhr.send();
    }
  </script>
</body>
</html>

方式二:canvas.todataurl()方法

实现原理:

使用canvas.todataurl()方法

需要解决图片跨域问题 image.crossorigin = '';

使用了jquery库的$.deferred()方法

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>js 图片转base64方式</title>
</head>
<body>
<p id="container2"></p>
  <script src="https://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    let imgsrc = "https://z649319834.github.io/learn_example/video_track/webvtt.jpg";

    //width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
    function getbase64image(img, width, height) {
      var canvas = document.createelement("canvas");
      canvas.width = width ? width : img.width;
      canvas.height = height ? height : img.height;
      var ctx = canvas.getcontext("2d");
      ctx.drawimage(img, 0, 0, canvas.width, canvas.height);
      var dataurl = canvas.todataurl();
      return dataurl;
    }
    function getcanvasbase64(img) {
      var image = new image();
      //至关重要
      image.crossorigin = '';
      image.src = img;
      //至关重要
      var deferred = $.deferred();
      if (img) {
        image.onload = function () {
          deferred.resolve(getbase64image(image));//将base64传给done上传处理
          document.getelementbyid("container2").appendchild(image);
        }
        return deferred.promise();//问题要让onload完成后再return sessionstorage['imgtest']
      }
    }
    getcanvasbase64(imgsrc)
      .then(function (base64) {
        console.log("方式二》》》》》》》》》",base64);
      }, function (err) {
        console.log(err);
      });
  </script>
</body>
</html>

demo展示

图片base64

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网