我正在开发一个 HTML 小部件,该小部件将嵌入 iPad 版 iBooks Author 中的 iBook 中。
我有一个简单的按钮可以在 iPad 上触发图像捕获,并且一切正常。
<div id="zeroDiv">
<input type="file" id="getPic" accept="image/*">
</div>
<div id="picWrapper">
<img id="image">
<div id="buttDiv">
<button id="picButt"><span class="buttText">Insert image</span>
</button>
</div>
</div>
和
$('#picButt').click(function () {
$('#getPic').trigger('click');
});
$(document).ready(function () {
$("#getPic").on("change", gotPic);
$("#image").load();
});
function gotPic(event) {
$("#image").attr("src", URL.createObjectURL(event.target.files[0]));
$("#picButt span").text("Change image");
}
拨弄https://jsfiddle.net/mikawaben/cq2yrh2z/
但是,当用户离开页面并返回时,图像会随着页面重新加载而丢失。我需要将图像存储在 localStorage 中。
我知道 http://jsfiddle.net/VXdkC/2/ 上的 fiddle (由本网站上的 Musa 提供)保存的代码可能是我的关键。
$('#addNote').click(function () {
var Title = $('#title').val();
var Message = $('#message').val();
var pic = document.getElementById("file").files[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>"+ "<p>" + Message + "<img src=" + imgURL + "></p> </div>");
var notes = $('#notes').html();
localStorage.setItem('notes', notes);
saveDataToLocalStorage(imgURL);
}
reader.readAsDataURL(pic);
return false;
});
//show content of notes in storage
$('#notes').html(localStorage.getItem('notes'));
return false;
但是尽管我花了几个小时摆弄它,但我还是没有让它工作。有人可以帮忙吗?
我还担心压缩问题。我是否需要使用 base64 编码或其他编码,以防图像大小导致整个系统崩溃?
最佳答案
只需检查页面加载时是否保存了图像并显示它。然后在选择时保存图像。
$(document).ready(function () {
$("#getPic").on("change", gotPic);
if (localStorage['url']){
$("#image").attr("src", localStorage['url']);
$("#picButt span").text("Change image");
}
});
function gotPic(event) {
var reader = new FileReader();
reader.onload = function(){
$("#image").attr("src", this.result);
localStorage['url'] = this.result;
$("#picButt span").text("Change image");
}
reader.readAsDataURL(event.target.files[0]);
}
关于javascript - 压缩捕获的图像并将其保存到 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29254321/