Y
Y
Yura Komarov2017-07-27 10:41:02
JavaScript
Yura Komarov, 2017-07-27 10:41:02

ArrayBuffer or how to create buffer from Base64 string?

Hello runet experts.
I'm reading the documentation https://developer.mozilla.org/ru/docs/Web/JavaScri...
and I can't figure out how to put into practice "Creating a Buffer From a Base64 String"
I understand that you can throw a base64 string into a buffer and get a link to it and attach it to the picture (so as not to write the entire base64 string into the picture). The basis of the assumption from the article "It is a link to the stream of" raw "binary data, but does not allow you to work with them directly."
Why do I need this:
a) I have 70 identical pictures on my page.
b) I need to save this picture in localStorage, and then read it out and attach it to 70 pictures again.
What am I doing:
a) I get a file from the user const file = e.target.files[0];
b) Read it like reader.readAsDataURL(file); (in order to be able to save in localStorage)
c) I write data to each picture
My questions:
a) How can I save this base64 to the buffer according to this article and add only a link to this buffer to the pictures.
b) And is it possible to do this, maybe I didn’t understand it so well.
c) And if possible, then a simple code example

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Larisa Moroz, 2017-07-27
@Yurajun

function base64ToArrayBuffer(base64) {
    var binary_string =  window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

A working example with extracting a saved image from localStorage into a src of seventy images: https://codepen.io/lmoroz/pen/yoNxRE?editors=0010
But we need to test what will be faster and less memory-intensive - just write data:base64 from localStorage to all src or toil with conversion to buffer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question