压缩并保存捕获到localStorage的图像

时间:2015-03-25 11:25:04

标签: javascript jquery image base64 local-storage

我正在开发一个HTML小部件,它将嵌入到iBooks for iBooks 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/的小提琴(由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编码或其他东西以防图像大小导致整个事件崩溃?

1 个答案:

答案 0 :(得分:1)

只需检查是否在页面加载时保存了图像并显示它。然后在选择时保存图像。

$(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]);   
}

https://jsfiddle.net/cq2yrh2z/1/

相关问题