I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
I have a PHP script that can encode a PNG image to a Base64 string.
I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
if you need to encode HTML image object, you can write simple function like:
To get base64 of image by id:
more here
Well, if you are using dojo, it gives us direct way to encode or decode into base64.
Try this:-
To encode an array of bytes using dojox.encoding.base64:
To decode a base64-encoded string:
I +1'ed Sunny's answer, but I wanted to contribute back a few changes I made for my own project in case anyone should find it useful. Basically I've just cleaned up the original code a little so JSLint doesn't complain quite as much, and I made the methods marked as private in the comments actually private. I also added two methods I needed in my own project, namely
decodeToHex
andencodeFromHex
.The code:
This question and it's answers pointed me to the right direction.
Especially with unicode atob and btoa can not be used "vanilla" and these days EVERYTHING is unicode ..
Directly from Mozilla, two nice functions for this purpose (tested with unicode and html tags inside)
These functions will perform lightning fast in comparison to raw base64 decoding using a custom javascript function as btoa and atob are executed outside the interpreter.
If you can ignore old IE and old mobile phones (like iphone 3?) this should be a good solution.
Internet Explorer 10+
Cross-Browser
jsFiddle
with Node.js
Here is how you encode normal text to base64 in Node.js:
And here is how you decode base64 encoded strings:
with Dojo.js
To encode an array of bytes using dojox.encoding.base64:
To decode a base64-encoded string:
bower install angular-base64
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.