2015-08-23 215 views
0

我有一張照片從Facebook圖形API上拉出來,我試圖將其上傳到我的數據庫,但我必須先將其轉換爲基本64位,我如何在angularJS或Javascript中執行此操作。我嘗試使用庫:https://github.com/ninjatronic/angular-base64但它沒有工作將圖像URL轉換爲base64

$scope.prof_pic_link = $base64.encode(data.picture.data.url); 
    $scope.prof_pic_link = encodeURIComponent($scope.prof_pic_link); 
+0

http://stackoverflow.com/a/22172860/1675954 –

+3

嘗試檢查此:http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – Grald

+1

http://jsfiddle.net/handtrix/xztfbx1m/ –

回答

-1

我用下面的函數用於編碼的二進制數據:

var base64_encode = function (data) { 
    // discuss at: http://phpjs.org/functions/base64_encode/ 
    // original by: Tyler Akins (http://rumkin.com) 
    // improved by: Bayron Guevara 
    // improved by: Thunder.m 
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 
    // improved by: Rafał Kukawski (http://kukawski.pl) 
    // bugfixed by: Pellentesque Malesuada 
    // example 1: base64_encode('Kevin van Zonneveld'); 
    // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' 
    // example 2: base64_encode('a'); 
    // returns 2: 'YQ==' 

    var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/='; 
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, 
     ac = 0, 
     enc = '', 
     tmp_arr = []; 

    if (!data) { 
     return data; 
    } 

    do { // pack three octets into four hexets 
     o1 = data.charCodeAt(i++); 
     o2 = data.charCodeAt(i++); 
     o3 = data.charCodeAt(i++); 

     bits = o1 << 16 | o2 << 8 | o3; 

     h1 = bits >> 18 & 0x3f; 
     h2 = bits >> 12 & 0x3f; 
     h3 = bits >> 6 & 0x3f; 
     h4 = bits & 0x3f; 

     // use hexets to index into b64, and append result to encoded string 
     tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); 
    } while (i < data.length); 

    enc = tmp_arr.join(''); 

    var r = data.length % 3; 

    return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); 
} 
+0

這會對url進行編碼,('http:// example.com/image.png' - >'aHR0cDovL2V4YW1wbGUuY29tL2ltYWdlLnBuZw =='這很容易用'btoa()')實現。你如何編碼圖像? (提示,[檢查重複](http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript)) – Kaiido

+0

你的意思是dataURL? –

+0

對於base64轉換後的圖像,dataUrl只是''data:image/png,base64;''頭部和圖像數據的base64值的組合。你的解決方案只是對atob方法的重寫,如果你只有圖像url,這是無用的。 – Kaiido