如何将图像存储在本地存储而不是路径?

时间:2014-06-24 10:02:06

标签: javascript jquery

我们可以将图像存储在本地存储中并从存储中获取图像。因为在本地存储中存储数量或者字符串能存储图像而不是路径吗? http://jsfiddle.net/sAH8w/

$(function(){
    $('#save').click(function(){
        alert('save')   
        localStorage.setItem("image", https://dl.dropboxusercontent.com/s/t2ywui846zp58ye/plus_minus_icons.png?m=);
    })

    $('#get').click(function(){
        alert('get');
        var image=localStorage.getItem("image");   
    })
})

1 个答案:

答案 0 :(得分:1)

  

您可以使用“canvas”元素。

     

//获取对图像元素的引用

     

var elephant = document.getElementById(“elephant”); // 采取行动   当图像加载时

     

elephant.addEventListener(“load”,function(){

     

var imgCanvas = document.createElement(“canvas”),           imgContext = imgCanvas.getContext(“2d”);

// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;

// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");

// Save image into localStorage
try {
    localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
    console.log("Storage failed: " + e);
} }, false);