get an image file with XMLHttpRequest and encode with base64

      var xhr = new XMLHttpRequest();
      var imgurl = "http://lh5.ggpht.com/-ZpKKJYkqobU/ULk2lb2yh5I/AAAAAAAAAAA/z74Pv1Zbfjc/photo.jpg";
      
      xhr.open('GET', imgurl, true);
      xhr.responseType = 'arraybuffer';//watch out this line!
      xhr.onload = function(){
        var blob = new Uint8Array(this.response);
        //encode with base64
        var uri = "data:image/jpeg;base64," + Base64.encode(blob);
        document.getElementById("myImage").src = uri;        
      };
      xhr.send();


following is the very simple Base64 encode algorithm

var Base64 = {
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

  // public method for encoding
  encode : function (input) {
      var output = "";
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      var i = 0;
      //input = Base64._utf8_encode(input); //comment out to encode binary file(like image)

      while (i < input.length) {

          chr1 = input[i++];
          chr2 = input[i++];
          chr3 = input[i++];

          enc1 = chr1 >> 2;
          enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
          enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
          enc4 = chr3 & 63;

          if (isNaN(chr2)) {
              enc3 = enc4 = 64;
          } else if (isNaN(chr3)) {
              enc4 = 64;
          }
          output = output +
                   Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
                   Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);
      }
      return output;
  }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值