Search code examples
javascripthtmlangularionic-frameworkweb-applications

What is the logic for sending the base64 string into image?


I have generated a Base64 string, which I have shared as an image using Capacitor FileSharer, for this I have used two approaches-

  1. img.split(',')[1],

This I have understood as how it is giving me the image file from removing the "data:image" from the string.

  1. img.replace(/^data:image\/[a-z]+;base64,/, "")

This I haven't understood properly as what functions it is performing to the string that I am getting a image file. Anyone If possible, do provide an explanation.

Though I have used both of them, and both works fine. It is only I am asking because ,If I am using any property in my project , I should now how it is actually working.

(PS- I am new to Javascript )


Solution

  • Introduction of Base64 encoding

    In computer science, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits (you can read more here).

    Where can we use Base64 encoding on images specifically?

    Basically, there are multiple advantages in using base64 images or even files such as pdf, csv, etc., in web interactions:

    1. For storying them easily in databases as string and retrieve them accordingly.
    2. In JSON or XML based web architectures (such as REST or SOAP) usually is hard to send images along side with form data. For example, sending profile picture along side with user form data such as username, password, first name, last name, etc., in JSON format.
    3. Security! Anyone who does not know anything about base64 encoding cannot open files easily as it should be.