我尝试将我放入localStorage中的图片用作我的Chrome扩展程序中的base64字符串,并以此为指导: How to save an image to localStorage and display it on the next page? 我将图像存储为我的options.js中的可选文件,并且它在会话期间的选项页面上是持久的。但在我的主Script.js中,相同的键始终为null。这给了我选项页面上的完整字符串,但是当我在主脚本中运行相同的代码时,每个其他页面都为null:
var dataImage = localStorage.getItem('imgData');
console.log(dataImage);
有没有关于本地存储的内容我不理解?
答案 0 :(得分:0)
**将图像保存为Base64。然后我将Base64字符串保存为我的localStorage值。
img1= document.getElementById('imgid');
imgResult= convertoBase64Image(img1);
localStorage.setItem("imgSaved", imgResult);
以下是将图像转换为Base64 sting的函数:
function convertoBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
new image.src =""
<img src="" id="newImage" />
检索图片的Javascript代码:
var Image = localStorage.getItem('imgSaved');
Img= document.getElementById('newImage');
Img.src = "data:image/png;base64," + Image ;