Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary data to base64 with javascript

Tags:

HTML5 enable you to store data locally which I think it is great. For example here is how you can use it:

        var store = window.localStorage;         store.setItem('foo', "hellow world");         var test = store.getItem('foo');         // test should = "hellow world" 

In html you can dynamically display an image by settig its source to:

     "data:image/jpg;base64," + (base64string) 

So my question is how can I convert binary data to a base64 string so that I can take advantage of html5 local storage?

For example it will be great if I could:

$.ajax({    url: 'someImage.png',    type: 'POST',    success: function (r) {                  // here I want to convert r to a base64 string !                 // r is not binary so maybe I have to use a different approach                 var data = ConvertToBase64(r);                    document.getElementById("img").src = "data:image/png;base64," + data;             }, }); 

I know I could solve this problem by wrapping the image around a canvas using html5 then converting that to base64string. also I can make a specific service on the server that will send a base64 string data of that image (someImage.aspx).I just want to know if it will by possible to retrieve binary data from a server and convert that to a base64 string.

like image 312
Tono Nam Avatar asked Jun 11 '12 15:06

Tono Nam


People also ask

Is BTOA () deprecated?

The Node btoa() and atob() functions are the only ones that have been deprecated. However, if you're working on the DOM code (front-end) and see this deprecated notice, you can use the window object to get around it.

What does BTOA do in Javascript?

btoa() The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).

What is base64 in Javascript?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.


1 Answers

To prevent 'InvalidCharacterError' error, you need to do this:

var base64EncodedStr = btoa(unescape(encodeURIComponent(rawData))); 
like image 95
Frane Poljak Avatar answered Oct 18 '22 19:10

Frane Poljak