2014-07-20 164 views
0
function convertImgToBase64(url){ 

    var canvas = document.createElement('CANVAS'); 
    var ctx = canvas.getContext('2d'); 
    var img = new Image; 
    img.crossOrigin = 'Anonymous'; 
    img.onload = function(){ 
    canvas.height = img.height; 
    canvas.width = img.width; 
     ctx.drawImage(img,0,0); 
     var dataURL = canvas.toDataURL('image/png',""); 
     alert(dataURL); 

     canvas = null; 
    }; 
    img.src = url; 



} 

var url_to_be_converted = "http://www.google.com/image/sample" 
convertImgToBase64(url_to_be_converted); 

Alert(dataURL)不顯示任何結果。是否在此處生成彈出窗口?如何解決這個問題?
有什麼不對?使用javascript將圖像轉換爲base64

+0

缺少分號裝的形象呢?應該是'var url_to_be_converted =「http://www.google.com/image/sample」;' – tillz

+0

不,這不是問題 – user3858217

+1

@tillz:分號在JavaScript中是可選的,儘管它們的省略有時會導致意想不到的問題。 –

回答

1

有一個跨源問題...嘗試使用此功能

function convertImgToBase64(url) 
{ 
    var canvas = document.createElement('CANVAS'); 
    img = document.createElement('img'), 
    img.src = url; 
    img.onload = function() 
    { 
     canvas.height = img.height; 
     canvas.width = img.width; 
     var dataURL = canvas.toDataURL('image/png'); 
     alert(dataURL); 
     canvas = null; 
    }; 
} 

我刪除的背景和我以不同的方式

+0

感謝它的工作! – user3858217