[英]Store Image from URL to localstorage
I have a JSON string as below which contains the path of an image. 我有一个下面的JSON字符串,其中包含图像的路径。 The image exists in the server 图像存在于服务器中
"send-sms":{
"menu_name":"Send",
"menu_icon":"http:\/\/example.com\/mob\/media\/com_abcd\/icons\/send.png"
}
This is my meta 这是我的中继
<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">
I want to store the image to a local session. 我想将图像存储到本地会话。 I use the below Javascipt where I pass the full image URL. 我使用下面的Javascipt传递完整的图像URL。 It always returns null. 它始终返回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);
};
}
Remember, you have an async
call. 记住,您有一个async
调用。
The code will run in the steps I have mentioned in the comments. 该代码将按照我在注释中提到的步骤运行。
In short, you are creating a second variable, also called data
and then doing nothing with it. 简而言之,您正在创建第二个变量,也称为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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.