[英]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.