html5本地存储图片方法

29681次浏览

前言

上一篇文件结尾,有同学问我本地存储图片方法,其实本地存储方式有很多,我们打开谷歌浏览器,查看源代码,在resources页签中,有web SQl ,indexedDB等等,我前面文章讲过Localstorage本地存储,我今天简单用Localstorage,简单的写一下存储图片的方法!

思路

我们知道Localstorage只能存储字符串,那么我们可以把图片转换为base64编码的字符串,不就可以存储了吗?

图片编码的数据一般以如下开头

data:image/gif;base64,base64编码的gif图片数据 
data:image/png;base64,base64编码的png图片数据 
data:image/jpeg;base64,base64编码的jpeg图片数据 
data:image/x-icon;base64,base64编码的icon图片数据 

关键是如何转换呢?

我们canvas中有个toDataURL()方法,貌似可以转换!拿我们就用这个方法试一试!

存储图片函数书写

function saveImg( key ){
   var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://b.hiphotos.baidu.com/baike/w%3D268%3Bg%3D0/sign=92e00c9b8f5494ee8722081f15ce87c3/29381f30e924b899c83ff41c6d061d950a7bf697.jpg"; // insert image url here

    img.crossOrigin = "Anonymous";

    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage( img, 0, 0 );
        localStorage.setItem( key, canvas.toDataURL("image/png") );
    }
    img.src = src;
    // make sure the load event fires for cached images too
    if ( img.complete || img.complete === undefined ) {
        img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        img.src = src;
    }
 }

获取图片函数书写

function get(div,key){//读取get(容器,图片)
    var srcStr = localStorage.getItem(key);
    var imgObj = document.createElement('img');
    imgObj.src = srcStr;
    div.appendChild(imgObj);
}

应用

    <input id="haorooms_btn" type="button" value="图片显示">
    <div id="haorooms_div"></div>

window.onload = function(){
    saveImg("savedImageData");
    var haoroomsbtn = document.getElementById('haorooms_btn');
    var oDiv = document.getElementById('haorooms_div');
    haoroomsbtn.onclick = function(){
        get(oDiv,"savedImageData");
    }
}   

案例下载

简单案例上传前端资料库了!

案例预览

案例下载

Tags: Localstoragehtml5

相关文章: