[英]How to convert image into base64 and store it in Local Storage
如何將選定的圖像轉換為base64,然后將其保存在本地存儲中以供以后使用。
var image = document.getElementById("image");
image.addEventListener('change', function() {
//How to
});
只要看一下這篇文章,他們就會確切地解釋您的需求: https : //hacks.mozilla.org/2012/02/saving-images-and-files-in-localstorage/
但是,它們不是使用base64編碼,而是使用canvas + toDataUrl()提取圖像數據,從而將圖像數據從Blob轉換為Data URL。
請注意從外部網站加載的圖像,crossOrigin策略可能會引發安全錯誤。 (請參閱22710627 )
// Get a reference to the image element
var elephant = document.getElementById("elephant");
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
希望這對您有所幫助:)
您可以使用HTML5:
創建一個畫布,將圖像加載到其中,然后使用toDataURL()獲取base64表示形式(實際上,它是一個數據:URL,但其中包含base64編碼的圖像)。
然后將此數據保存到lcoalStorage:
localStorage.setItem('imgBase64', this.yourVariable);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.