I've seen several tutorial explaining how to convert binary image into encode64 representations:
var image = new Buffer(bl.toString(), 'binary').toString('base64');
My question is, how to return this string representation, back to it's buffer's binary data.
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string.
The Base64 decoding process is very much similar to the encoding process. All you need to do is create a buffer from the Base64 encoding string by using base64 as the second parameter to Buffer. from() and then decode it to the UTF-8 string by using the toString() method.
This question has some helpful info: How to do Base64 encoding in node.js?
The Buffer class itself does the conversion:
var base64data = Buffer.from('some binary data', 'binary').toString('base64'); console.log(base64data); // -> 'c29tZSBiaW5hcnkgZGF0YQ==' var originaldata = Buffer.from(base64data, 'base64'); console.log(originaldata); // -> <Buffer 73 6f 6d 65 20 62 69 6e 61 72 79 20 64 61 74 61> console.log(originaldata.toString()); // -> some binary data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With