如何通过使用jQuery从图像URL本地存储图像?

时间:2018-08-28 11:29:15

标签: javascript jquery tizen tizen-web-app

我想在本地存储图像并将其用于tizen应用程序中的任何地方。

我尝试使用画布,但是画布数据uri无法显示URL中具有的确切图像。

我正在使用的代码段。

var img = new Image();
img.src = imageURL;

var canvas = document.createElement('canvas');

document.body.appendChild(canvas);

var context = canvas.getContext('2d');

context.drawImage(img, 0, 0);

var data = context.getImageData(x, y, img.width, img.height).data;

localStorage.setItem('image', data);

1 个答案:

答案 0 :(得分:1)

您的代码无效,因为您要将array保存到localStorage。代替context.getImageData(),您必须使用canvas.toDataURL(),然后将dataURL转换为Base64字符串图像。之后,您可以将其保存到localStorage

您的图片必须在线并且与脚本位于相同的域中。这是因为Cross-origin resource sharing (CORS)。但是,如果您之前在dataURL中像我一样转换了图像,那么您应该没有任何问题。

您今天(2018年)只能以在线模式访问localStorage。请阅读:

完整示例

codepen.io 上查看此工作示例(链接至示例),因为在StackOverflow上,片段被沙盒化,因此,我们无法访问localStorage

var canvas = document.createElement('canvas');
var image = new Image();
var ctx = canvas.getContext('2d');

image.onload = function()
{
    canvas.width = image.width;
    canvas.height = image.height;

    ctx.drawImage(image, 0, 0);

    var dataURL = canvas.toDataURL('image/png');

    var Base64StringImage = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

    localStorage.setItem('image', Base64StringImage);

    //read from localStorage:
    document.querySelector('img').src = 'data:image/png;base64,' + localStorage.getItem('image');
};

image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAADnElEQVRYhaWXz2/cRBTHP/Y4zka0ShPQJluJLkl/0EsSl24OCAgRFQoH1Ir/oNmeEJdScYUDXOitSBxASFmQ4MSJay6EtojLgvIDCUKhaQIipCI/SlKy690Zc2jWa3ttT4Tn9p3v6H3fe/Pm2c/wPM/jYC25n1Nnl5L9emuLDbnIgBj18ba6S5857ONPHz5P3MqbIzh2meNi3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