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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use
btoa()andatob()to convert to and from base64 encoding.There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.atob()returns a “string” where each character represents an 8-bit byte – that is, its value will be between0and0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.See also:
Most comments here are outdated. You can probably use both
btoa()andatob(), unless you support really outdated browsers.Check here: