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

标签 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");   
    })
})

最佳答案

You can make use of "canvas" element.

// Get a reference to the image element

var elephant = document.getElementById("elephant"); // Take action when the image has loaded

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);

关于javascript - 如何将图像存储在本地存储而不是路径中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24383723/

相关文章:

javascript - 如何基于stdout和stderr验证来自nodejs的 Angular 后调用

jquery - 一份 UL 列表拆分成固定高度的多列

javascript - jQuery 多重切换

jquery - 仅使用 JQuery 更新 Twitter (OAuth)

jquery - 调用jquery函数onclick事件

javascript - 如何用多个事件处理程序触发一个函数(更改)

javascript - 调用方法时出错 'addNewDriveToSadranTable' : Internal server error [500]

php - 从网络到游戏

javascript - 将 js 正则表达式转换为 python 正则表达式

javascript - Bootstrap 弹出窗口更新内容