2

I have a save image function that looks like this:

async saveImage(image: Blob, key: string) {
    // using: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
    const content = await image.text();
    window.localStorage.setItem(key, content);
}

Now I like to create a load Image function looking like this:

async loadImage(key: string) : Blob {
    const item = window.localStorage.getItem(key);
    const imageBlob = ???
    return imageBlob;
}

How can I convert the USVString that was generated by Blob.text() back to a new Blob()?

jwillmer
  • 3,570
  • 5
  • 37
  • 73
  • 1
    The [`Blob` constructor takes a `USVString`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob).... Note that saving an actual image file like PNG or JPEG as text isn't going to work, since `text()`, as the linked page notes, outputs the bytes interpreted as UTF-8 encoded characters. The bytes in an image do not stay within those parameters. – Heretic Monkey Sep 02 '20 at 21:27
  • 1
    See [Save a File Image to localstorage HTML](https://stackoverflow.com/q/31850732/215552) for instructions on how to do what you want to do. – Heretic Monkey Sep 02 '20 at 21:35
  • @HereticMonkey Works perfectly. If you put your comments in an answer I'm happy to close this question :) – jwillmer Sep 02 '20 at 22:30
  • Found an even better solution: https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript – jwillmer Sep 03 '20 at 11:27
  • Does this answer your question? [Creating a BLOB from a Base64 string in JavaScript](https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript) – Heretic Monkey Sep 03 '20 at 11:32

0 Answers0