DEV Community

Davy Chen
Davy Chen

Posted on

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:

  1. TextEncoder().encode() the text.
  2. base64 encode.
  3. Save into DB and over to Frontend.

Frontend:

  1. Retrieve encoded text from Backend.
  2. base64 decode.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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

Backend(PHP):

  1. rawurlencode() the text.
  2. base64_encode() encode.
  3. Save into DB and over to Frontend.

Frontend(JavaScript):

  1. Retrieve encoded text from Backend.
  2. atob()(base64 decode)
  3. decodeURIComponent().

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

Top comments (2)

Collapse
 
mardeg profile image
Mardeg

I used some of this for a tool to create favicons using emojis within SVG:
emojicons.glitch.me/

Collapse
 
davychxn profile image
Davy Chen

That's a useful tool! And I'll consider joining the webring.