思路:使用html5的新特性:canvas, 該對象有一個toDataURL() 方法,能夠將畫布內容轉換成一個指定編碼的數據。咱們能夠先根據圖片的路徑將圖片「畫出來」,而後獲得圖片的數據。html
具體的TypeScript 代碼:html5
1 convertImgToBase64(url, callback) { 2 var canvas = document.createElement('canvas'); 3 canvas.width = 1024; 4 canvas.height = 768; 5 var ctx = canvas.getContext('2d'); 6 var img = new Image; 7 img.crossOrigin = 'Anonymous'; 8 img.onload = function() { 9 canvas.height = img.height; 10 canvas.width = img.width; 11 ctx.drawImage(img, 0, 0); 12 var dataURL = canvas.toDataURL('image/jpeg'); 13 callback.call(this, dataURL); 14 canvas = null; 15 }; 16 img.src = url; 17 }
調用的時候:canvas
this.convertImgToBase64(filePath, function(base64Image) { //filePath 即爲圖片的路徑 //base64 是轉化後的圖片數據 });