get an image file with XMLHttpRequest and encode with base64

来源:互联网 发布:王充 论衡 知乎 编辑:程序博客网 时间:2024/06/07 23:49
      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
原创粉丝点击