Encode/Decode emojis into/from base64

davychxn

Davy Chen

Posted on May 8, 2024

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

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
davychxn
Davy Chen

Posted on May 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About