圖片轉成Base64


var img = "imgurl";//imgurl 就是你的圖片路徑  

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;
img.setAttribute('crossOrigin', 'anonymous');
image.onload = function(){ var base64 = getBase64Image(image); console.log(base64); } 

 

 

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

經過查閱和分析,發現這個其實是由於視頻文件所在的域和圖片和頁面所在域不同,出現跨域傳輸的問題。

解決方案1.

如果想使用toDataURL()生成圖片文件的話,在canvas繪圖過程中使用的圖片應該是當前域下的。

解決方案2.

訪問的服務器允許,資源跨域使用,也就是說設置了CORS跨域配置,Access-Control-Allow-Origin

然后在客戶端訪問圖片資源的時候


img.setAttribute('crossOrigin', 'anonymous');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM