将图像从URL存储到localstorage

时间:2016-02-13 18:50:33

标签: javascript local-storage

我有一个JSON字符串,如下所示,其中包含图像的路径。图像存在于服务器

"send-sms":{
   "menu_name":"Send",
   "menu_icon":"http:\/\/example.com\/mob\/media\/com_abcd\/icons\/send.png"
}

这是我的元

<meta http-equiv="Content-Security-Policy" 
      content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: http://example.com">

我想将图像存储到本地会话中。我使用下面的Javascipt传递完整的图像URL。它总是返回null。

function getImageData(imgpath){
    var img = new Image();
    img.src = imgpath;
    var data = null;

    img.load = function() {
        var canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);
        data = context.getImageData(x, y, img.width, img.height).data;
        console.log(data);
        localStorage.setItem('mysession_imag', data);
    };

}

1 个答案:

答案 0 :(得分:1)

请记住,您有一个async电话。

代码将按照我在评论中提到的步骤运行。

简而言之,您正在创建第二个变量,也称为data,然后对其执行任何操作。

function getImageData(imgpath){
    var img = new Image();
   img.src = imgpath;

    // Step 1: Yes, data is `null`.  You are setting it that way.
    data = null;

    img.load = function() {
        var canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);

        // Step 3:  You are creating a NEW data variable
        var data = context.getImageData(x, y, img.width, img.height).data;

        // Step 4: And doing nothing with it.
    };

    // Step 2: You are storing the `null` from step 1
    localStorage.setItem('mysession_imag', data);
}