HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can you encode/decode a string to Base64 in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowdecodecanbase64encodestringjavascript

Problem

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.

Solution

You can use btoa() and atob() 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 between 0 and 0xff. 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:

  • How do I load binary image data using Javascript and XMLHttpRequest?



Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

Check here:

  • https://caniuse.com/?search=atob



  • https://caniuse.com/?search=btoa



In 2025, all "evergreen" browsers offer toBase64 and fromBase64 to convert a Uint8Array to and from Base64 string. If your input is a Unicode string, not raw bytes, you can convert it to and from Uint8Array (of UTF-8 bytes) by TextEncoder and TextDecoder. See also another answer about this.

Context

Stack Overflow Q#246801, score: 1413

Revisions (0)

No revisions yet.