我正在尝试使用 localStorage 保存一个图像或多个图像以便稍后检索并上传到服务器。
当前相机代码如下:
function capturePhoto() {
navigator.camera.getPicture(onCameraSuccess, onCameraFail, {quality: 70, destinationType : Camera.DestinationType.DATA_URL});
}
function onCameraSuccess(imageData) {
//In our success call we want to first process the image to save in our image box on the screen.
var image = document.getElementById('image');
image.src = "data:image/jpeg;base64," + imageData;
//Create a new canvas for our image holder
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = image.width;
imgCanvas.height = image.height;
// Draw image into canvas element
imgContext.drawImage(image, 0, 0, image.width, image.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
// localStorage.setItem(“savedImage”, imgAsDataURL);
localStorage.setItem("savedImage", imageData);
alert('Image Saved');
}
catch (e) {
alert("Storage failed: " + e);
}
var imageStorage = localStorage.getItem("savedImage");
// myCardHolder= document.getElementById(“m1-cardStorage-image1″);
// Reuse existing Data URL from localStorage
var imageInfo = document.getElementById('image');
imageInfo.src = "data:image/jpeg;base64," + imageStorage;
}
这会触发相机,捕获的图像将显示到
<img id="image" src=""></img>
它还绘制一个 Canvas 来将图像输出到其中。我真正想要实现的是捕获图像 base64 数据,以便能够将其存储到数组中,以便可以从服务器上传/下载它。
理想情况下,我想完全避免向用户显示图像,而只需存储图像数据
我可能有点误解了 localStorage/camera api,所以任何指针都会很好。
在存储数据之前是否必须将图像输出到元素中?如果我可以将其输出到可能永远不需要显示的 Canvas 中,并从 Canvas 元素中提取数据?
最佳答案
Does the image HAVE to be output into an element before the data can be stored?
无论如何,在这种情况下根本不会。您已经收到了 Base64 数据形式的图像,因此只需直接存储即可。
问题:
- 如果 datauri 太长,浏览器可能会 chop
- 如果浏览器没有在字符串级别上 chop 数据,则数据可以由 localstorage 本身进行 chop ,本地存储本身有大小限制(我认为目前大多数浏览器的大小约为 5 mb,但这里没有标准)
- 字符串每个字符使用两个字节,因此存储实际上是一半
更好的本地存储是使用indexedDB。
当您读取base64数据时,您必须使用图像来显示数据。只需像使用 data:... 等一样添加前缀,并记住使用正确的文件类型。
关于javascript - LocalStoragephonegap相机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492390/