Javascript將圖片的絕對路徑轉換爲base64編碼chrome
咱們能夠使用canvas.toDataURL的方法將圖片的絕對路徑轉換爲base64編碼;在這咱們引用的是淘寶首頁一張圖片以下:canvas
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";跨域
咱們以下編寫代碼:服務器
function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataURL = canvas.toDataURL("image/"+ext); return dataURL; }
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg"; var image = new Image(); image.src = img; image.onload = function(){ var base64 = getBase64Image(image); console.log(base64); }
chrome 運行以下所示:測試
經過搜索明白,咱們使用的是淘寶服務器上的一張圖片,在本地服務器下訪問,結果出現圖片跨域的問題;爲止,咱們能夠把圖片放在本地服務器下便可解決上面的跨域問題;好比我如今將淘寶服務器下的圖片保存在本地服務器下;以下代碼便可解決:編碼
var img = "http://127.0.0.1/base64/1.jpg"; function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataURL = canvas.toDataURL("image/"+ext); return dataURL; } var image = new Image(); image.src = img; image.onload = function(){ var base64 = getBase64Image(image); console.log(base64); }
可是有時候咱們想引用其餘服務器下的圖片該如何解決呢?咱們能夠使用下面這一句代碼在chrome和firefox下生效,在目前safari6如下貌似不支持;以下代碼:spa
image.crossOrigin = '';firefox
全部代碼以下:code
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg"; //var img = "http://127.0.0.1/base64/1.jpg"; function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataURL = canvas.toDataURL("image/"+ext); return dataURL; } var image = new Image(); image.crossOrigin = ''; image.src = img; image.onload = function(){ var base64 = getBase64Image(image); console.log(base64); }
如上代碼在chrome和firefox下,經測試生效,在safari目前不支持;cdn