带有图像的本地存储

发布于 2024-11-26 19:10:50 字数 108 浏览 1 评论 0原文

我想在html5的本地存储中保存一个图像url,然后想在网页上设置该图像,并设置到另一个网页的链接(该链接地址也在本地存储中)但是我该怎么做

Update1 : 没有base64可以吗?

I would like to save an image url in the localstorage of html5 and then would like to set that image on a web page and also set a link to another webpage (that link addres is also in the localStorage) But how can I do that

Update1: Is it possible without base64?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤 2024-12-03 19:10:50

是的,你做错了!

您需要使用 base64 中的图像进行类似的操作:

<script>
var hero;

if (localStorage.getItem('heroImg')) {
    hero = localStorage.getItem('heroImg');
}
else {
    hero = '/9j/4AAQSkZJRgABAgAAZABkAAD/7    /.../    6p+3dIR//9k=';
    localStorage.setItem('heroImg', hero);
}

document.getElementById("hero-graphic").src = 'data:image/png;base64,' + hero; < /script>

</script>

相应的 HTML Image 元素:

<img id="hero-graphic" alt="Blog Hero Image" src="" / >

Yep you are doing it wrong!

You need something like this using image in base64:

<script>
var hero;

if (localStorage.getItem('heroImg')) {
    hero = localStorage.getItem('heroImg');
}
else {
    hero = '/9j/4AAQSkZJRgABAgAAZABkAAD/7    /.../    6p+3dIR//9k=';
    localStorage.setItem('heroImg', hero);
}

document.getElementById("hero-graphic").src = 'data:image/png;base64,' + hero; < /script>

</script>

The corresponding HTML Image element:

<img id="hero-graphic" alt="Blog Hero Image" src="" / >
于我来说 2024-12-03 19:10:50

我相信,如今,在 localStorage 中存储二进制数据的唯一可靠方法是保留 Base64 编码的字符串。但您应该记住,localStorage 是有限的,并且图像可能很重(base64 使它们更重)。

我猜你正在尝试缓存你的图像。在几乎所有情况下,最好只设置正确的 http 标头,让浏览器为您完成所有肮脏而乏味的工作。相信我,情况好多了。

I believe, nowadays, the only reliable way to store binary data in localStorage - is to keep base64-encoded string. But you should keep in mind that localStorage is limited, and images can be heavy (and base64 makes them heavier).

I guess you are trying to cache your images. It would be better in almost all cases just to set properly http headers, to let the browser do all the dirty and tedious work for you. Trust me, it is way better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文