简体   繁体   English

如何将图像存储为 base64 以从本地数据中使用,而不必将其存储在服务器上? 需要重绘海量图片,甚至离线

[英]How do I store an image as base64 to be used from local data instead of having to store it on a server? Need to redraw a massive image, even offline

SOLUTION: simply store the base64 as the image source on an HTML image tag and then hide that image.解决方案:只需将 base64 作为图像源存储在 HTML 图像标签上,然后隐藏该图像。 Thanks, Kaiido!谢谢,凯多!

I need to store an image as pixel data in the most performant way possible at it's highest possible resolution.我需要以尽可能高的分辨率以尽可能高的性能将图像存储为像素数据。 To accomplish I have been fetching the image from imgur and converting to base64 like so:为了完成,我一直从 imgur 获取图像并转换为 base64,如下所示:

async function toBase64(file) {
   return new Promise((resolve, reject) => {
   const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
   });
}

async function getBlob(){
   const blob = fetch("https://i.imgur.com/sOmEuRl.jpg")
      .then(function (response) {
         return response.blob();
      })
      .catch(function(err){
          console.log(err)
      })
          
   return blob
}

const blob = await getBlob()
const base64 = await toBase64(blob);
const src = base64

It works tremendously but I need the project I'm working on to be usable offline.它非常有效,但我需要我正在处理的项目可以离线使用。 Naturally I'm encountering CORS errors when trying to use a local file URL so I'm completely out of ideas at this point.自然地,我在尝试使用本地文件 URL 时遇到了 CORS 错误,所以我现在完全没有想法。

I've tried loading the image using an img tag in the html but that gives the same CORS error, of course.我已经尝试使用 html 中的 img 标签加载图像,但这当然会产生相同的 CORS 错误。

Is there any way I can retrieve and store the data locally instead of retrieving it from a server?有什么方法可以在本地检索和存储数据,而不是从服务器检索数据? I've tried reading the pixel data and then writing it to a new file as an array using node, but the resulting file is so massive I can't do anything with it...我尝试读取像素数据,然后使用节点将其作为数组写入新文件,但生成的文件太大了,我无法用它做任何事情......

Thanks for your time.谢谢你的时间。

Base64 in LocalStorage is definitely not "the most performant way" to store an image, nor will it allow the storage of big files. LocalStorage 中的 Base64 绝对不是存储图像的“最高效方式”,也不允许存储大文件。

If I understand your case correctly (the need to be able to navigate your site even when offline), then the correct solution is to如果我正确理解您的情况(即使离线也需要能够浏览您的网站),那么正确的解决方案是

  • register a ServiceWorker,注册一个 ServiceWorker,
  • make this ServiceWorker store all the required resources, including your images, in the browser's cache through the Cache API ,让这个 ServiceWorker 通过Cache API在浏览器的缓存中存储所有需要的资源,包括你的图片,
  • make it retrieve the resources from the cache when your page fetches it again (eg at next reload).让它在您的页面再次获取它时从缓存中检索资源(例如,在下次重新加载时)。

More info available at https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps and particularily for this matter at https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers更多信息可在https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps获得,特别是在https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers

Now, you may be in a rush and not wanting to build a full PWA setup.现在,您可能很着急,不想构建完整的 PWA 设置。 In that case, the best solution to store binary data (image files included) in a semi-persistent way is to use the IndexedDB API (IDB).在这种情况下,以半持久方式存储二进制数据(包括图像文件)的最佳解决方案是使用 IndexedDB API (IDB)。 I invite you to read this previous answer of mine showing how to use Mozilla's library localforage which helps a lot dealing with IDB.我邀请您阅读我以前的回答,展示如何使用 Mozilla 的库localforage ,这对处理 IDB 有很大帮助。



And... turns out I didn't understand the case correctly.而且......原来我没有正确理解这个案子。 (I leave the first section anyway because who knows, it may help others). (无论如何我都会离开第一部分,因为谁知道,它可能会帮助其他人)。

So what OP actually wants is a standalone page, and for this, there is no need to "store" the image anywhere, it suffices to make it part of the markup directly, and this is actually one of the only cases where a data: URL is useful.所以 OP 真正想要的是一个独立的页面,为此,不需要在任何地方“存储”图像,直接使其成为标记的一部分就足够了,这实际上是data:网址很有用。

So you'd keep your code that generates the data: URL, but only as a tool for building your HTML file.因此,您将保留生成data: URL,但仅作为构建 HTML 文件的工具。 The HTML file would not contain this code but only the produced data: URL: HTML 文件将不包含此代码,而仅包含生成的data: URL:

 async function toBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); }); } function getBlob(){ return fetch("https://i.imgur.com/sOmEuRl.jpg") .then(function (response) { return response.blob(); }) .catch(function(err){ console.log(err); return Promise.reject(err); }); } (async () => { const blob = await getBlob() const base64 = await toBase64(blob); const src = base64; const HTMLMarkup = `<!DOCTYPE HTML> <html> <body> <h1>Your HTML page</h1> <img src="${src}" alt="an image"> <!-- your normal HTML content --> </body> </html>`; const HTMLFile = new Blob([HTMLMarkup], { type: "text/html" }); const HTMLSrc = URL.createObjectURL(HTMLFile); document.querySelector("iframe").src = HTMLSrc; document.querySelector("pre").textContent = HTMLMarkup; })();
 <iframe></iframe> <pre></pre>


But maybe , I'm still not understanding your situation completely and all you need is actually to save that file on your hard-drive, in the same directory as your file (or in a sub-folder of the one where your index.html file is).也许,我仍然不完全了解您的情况,您实际上需要将该文件保存在硬盘驱动器上,与您的文件在同一目录中(或在 index.html 所在目录的子文件夹中)文件是)。 Even if served through file:// all modern browsers accept to load an <img> if it meets this "same/sub-folder" condition.即使通过file://提供服务,如果<img>满足此“相同/子文件夹”条件,所有现代浏览器都接受加载。

Ps: If it's only for your usage, you may also consider starting a local server on your machine. ps:如果仅供你使用,你也可以考虑在你的机器上启动一个本地服务器。 If you continue doing some web-development you'll very soon find out that you need one.如果你继续做一些网络开发,你很快就会发现你需要一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将图像转换为base64并将其存储在本地存储中 - How to convert image into base64 and store it in Local Storage 如何在Java文件中将base64作为图像存储在文件系统中 - How to store base64 as an image in file system in Javascript 如何将base64字符串转换为图像并使用javascript存储在变量中 - How to convert base64 string to image and store in a variable with javascript 如何在SQL Server中存储Base64数据 - How to store base64 data in sql server 如何在javascript中使用http.post将图像发送到服务器并在mongodb中存储base64 - how to send image to server with http.post in javascript and store base64 in mongodb 将本地图像转换为base64数据 - convert local image to base64 data 如何将图像从 NodeJS 缓冲区 object 转换为 JavaScript 中的 base64 以便它可以在<img> src 属性? - How do I convert an image from a NodeJS Buffer object to base64 in JavaScript so it can be used in the <img> src attribute? 如何将base64数据作为png图像保存到服务器? - How to save base64 data as png image to server? 如何从JavaScript中的Base64图像获取图像尺寸? - How do I get image dimensions from a Base64 Image in JavaScript? 我可以安全地将base64图像存储在本地存储中吗? - Can I safely store base64 images in local storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM