如何存储和检索图像到localStorage? [英] How to store and retrieve image to localStorage?

查看:203
本文介绍了如何存储和检索图像到localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以为我有这个,但没有。目标:拍摄照片(保险卡),保存在本地,稍后检索。

Thought I had this, but no. The goal: snap a photo (insurance card), save it locally, and retrieve it later.

// Get a reference to the image element
var elephant = document.getElementById("SnapIt_mobileimage_5");

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 );
 console.log( 'Did that' );
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("data:image/jpg;base64,");

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

//Did it work?
var pic = localStorage.getItem("elephant");

console.log( elephant );
console.log( pic );

每个步骤成功,最终输出为:

Each step succeeds, the final output is:

<img id="SnapIt_mobileimage_5" class=" SnapIt_mobileimage_5" name="mobileimage_5" dsid="mobileimage_5" src="files/views/assets/image/IMG_0590.JPG">
 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA

在新页面上

var policy_shot = localStorage.getItem( 'elephant' );
console.log( policy_shot );

$('#TestScreen_mobileimage_1').src = policy_shot ;

它记录二进制文件:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUg ....


  1. 是否有更简单的方法?

  2. getItem(二进制)前面的数据:image / png;而不是数据:image / jpg?

  3. 这是为什么它不显示,还是我做了其他错误?


推荐答案

1)这是唯一可以将图像转换为字符串的方式 FileReader ,请参阅下文)。

1) This is the only way you can convert an image into a string locally (with the excpetion of files loaded with FileReader, see below). Optionally you need to use the server to do it.

2)要获取JPEG图片,您需要使用如下参数:

2) To get a JPEG image you need to use the argument like this:

var datauri = imgCanvas.toDataURL("image/jpeg", 0.5); //0.5 = optional quality

不要使用 data:... ,因为它将无效,它会产生默认的PNG,你可以在结果中看到。 toDataURL()只能接受一个类型,即。 image / png image / jpeg 等。

don't use data:... in the argument as that will be invalid and it will produce the default PNG as you can see in your result. toDataURL() can only take a type, ie. image/png, image/jpeg etc.

3)

如果您的图片是从其他来源(scheme,server ...)或使用本地引用文件( file:// / my / path / 等)CORS插入并阻止你创建一个数据uri,即:图像将是空的(并且为此不可见)。

If your image was loaded from a different origin (scheme, server ...) or by using local referenced files (file://, /my/path/ etc.) CORS kicks in and will prevent you from creating a data-uri, that is: the image will be empty (and therefor invisible).

对于外部服务器您可以通过提供 crossOrigin 属性来请求跨图元使用权限:

For external servers you can request permission to use the image from a cross-origin by supplying the crossOrigin property:

<img src="http://extrernalserver/...." crossOrigin="anonymous" />

或代码( img.crossOrigin ='anonymous'; ),然后设置 src

or by code (img.crossOrigin = 'anonymous';) before setting the src.

然而,服务器允许或拒绝请求

It's however up to the server to allow or deny the request.

如果它仍然不起作用,您将需要通过代理加载您的镜像(f.ex.您的服务器上可以加载和外部图像的页面

If it still doesn't work you will need to load your image through a proxy (f.ex. a page on your server that can load and the image externally and serve it from your own server).

或者如果您有权访问服务器的配置,您可以添加特殊访问允许标头(访问控制-Allow-Origin:* ,请参阅下面的链接了解更多详情)。

Or if you have access to the server's configuration you can add special access allow headers (Access-Control-Allow-Origin: *, see link below for more details).

CORS(跨原始资源共享)是一种安全机制,不能以这些方式以外的方式解决。

CORS (Cross-Origin Resource Sharing) is a security mechanism and can't be worked around other than these ways.

对于本地文件,您需要使用 FileReader - 这可能是一个优势 FileReader 附带一个方便的方法: readAsDataURL()

For local files you will need to use FileReader - this can turn out to be an advantage as FileReader comes with a handy method: readAsDataURL(). This allow you to "upload" the image file directly as a data-uri without going by canvas.

请参阅这里的范例:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

不幸的是,您不能只从代码中选择文件 - 您需要提供一个输入元素或放置区域,以便用户可以选择文件

Unfortunately you can't just pick the files from code - you will need to provide an input element or a drop zone so the user can pick the files (s)he want to store.

如果所有这些步骤都达到您实际获得的程度image

If all these steps are fulfilled to the degree that you actually do get an image the problem possibly is in the other end, the string being truncated being too long to store.

您可以通过检查存储字符串之前和之后的长度来验证如果已被剪切:

You can verify by checking the length before and after storing the string to see if it has been cut:

console.log(imgAsDataURL.length);
... set / get ...
console.log(pic.length);

其他可能性:

    $ b $ $ b
  • The image element is not properly defined.
  • A bug in the browser
  • A bug in the framework

(我认为我涵盖了大多数典型的陷阱?)

(I think I covered most of the typical pitfalls?)

strong>(missed one,sort of .. ;-p)

Update (missed one, sort of.. ;-p)

OP在框架中找到一个特定的内容,我将在这里包括以供将来参考:

OP found a specific in the framework which I'll include here for future reference:


最后,问题是 $('#TestScreen_mobileimage_1')。src =
policy_shot; code>我使用Appery.io,他们不支持 .src

$('#TestScreen_mobileimage_1')。attr(src,policy_shot);

最后一点: localStorage 在存储图像方面非常有限。典型的存储空间为2.5 - 5 mb。每个char存储需要2个字节,存储编码为base-64的数据uri比原始的大33% - 所以空间将是稀缺的。查看索引的数据库,Web SQL或File API,以获得良好的替代方案。

A final note: localStorage is very limited in regards to storing images. Typical storage space is 2.5 - 5 mb. Each char stored takes 2 bytes and storing a data-uri encoded as base-64 is 33% larger than the original - so space will be scarce. Look into Indexed DB, Web SQL or File API for good alternatives.

这篇关于如何存储和检索图像到localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆