Encode/Decode emojis into/from base64

Encode/Decode emojis into/from base64

Many users like to use emojis when posting messages to your website. As Web developer we should allow and encourage such kind of usage. Because it’s funny!😊

And some websites may have the need retrieving messages from backend being base64-coded.

But most of emojis are UTF-16 code. base64 can only work with UTF-8 or ASCII code. You can’t encode UTF-16 into base64 directly!

The idea is to convert the text containing emojis into a piece of intermediate code in the form of ASCII first!

If you use JavaScript at both ends, you can do this:

Backend:

TextEncoder().encode() the text.

base64 encode.
Save into DB and over to Frontend.

Frontend:

Retrieve encoded text from Backend.

base64 decode.

TextDecoder().decode.

Then you’ll see the emojis. 😀

But if you use another language at backend, say PHP, you don’t always find an alternative of TextEncoder there. Instead we can use URL encoding/decoding at backend/frontend.

Document of encodeURIComponent() says:

It encodes a URI by replacing each instance of certain characters
by one, two, three, or four escape sequences representing the
UTF-8 encoding of the character

In other words, it converts emojis code into ASCII, which is perfectly compitable with base64. Here is what we can do:

Backend(PHP):

rawurlencode() the text.

base64_encode() encode.
Save into DB and over to Frontend.

Frontend(JavaScript):

Retrieve encoded text from Backend.

atob()(base64 decode)

decodeURIComponent().

Then we can see the emojis on webpage, even mixed with other UTF-8 text. 😎

Leave a Reply

Your email address will not be published. Required fields are marked *