Base64 is a binary-to-text encoding scheme. It's used to represent binary data (like images, files, or any kind of non-text data) in an ASCII string format using only readable characters. It’s commonly used when you need to transmit or store data over media that are designed to deal with text (like email or URLs).
Why is it called "Base64"?
Because it uses 64 different characters to represent the data:
Uppercase letters: A–Z
(26 characters)
Lowercase letters: a–z
(26 characters)
Digits: 0–9
(10 characters)
Two symbols: +
and /
(or sometimes -
and _
in URL-safe Base64)
Example
Say you want to encode the word Cat
:
Convert it to binary:
C
= 01000011
a
= 01100001
t
= 01110100
So together: 01000011 01100001 01110100
Break that into 6-bit chunks:
Convert each chunk to Base64 (by index in the Base64 alphabet):
010000
= 16 → Q
110110
= 54 → 2
000101
= 5 → F
110100
= 52 → 0
So Base64 of Cat
= Q2F0
Common Uses
Embedding images in HTML/CSS (as data URIs)
Sending email attachments (MIME)
Storing binary data in JSON or XML
Basic HTTP authentication headers
Let's try to understand the conversion of Image into Base64 :
Step 1: I have a file input control which is used for uploading the image
Step 2 : Below is the jQuery code to upload a file, validate it (type and size), and convert it into a Base64 string. If the uploaded file is an image, it will also be previewed inside the #divUserLogo
container.
$("#UserLogoPic").change(function () {
$("#divUserLogo").show();
LogoName = $('#UserLogoPic').val().replace(/C:\\fakepath\\/i, '');
LogoExt = LogoName.substr(LogoName.lastIndexOf('.') + 1);
var mb = ((this.files[0].size) / 1024) / 1024;
if (LogoExt.toUpperCase() != "PNG" && LogoExt.toUpperCase() != "JPG" &&
LogoExt.toUpperCase() != "JPEG") {
ClearLogoPic();
alert("Image type should be PNG,JPG,JPEG.");
}
else if (mb > 5) {
ClearLogoPic();
alert("Logo Size should be less than 5 MB.");
}
else {
readURL(this);
}
});
function readURL(input) {
inputFile = input;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
base64Img = e.target.result;
$("#UserLogo").attr("src", base64Img);
var base64Arr = base64Img.split(',');
base64Img = base64Arr[base64Arr.length - 1];
}
reader.readAsDataURL(input.files[0]);
}
}
function ClearLogoPic() {
$("#UserLogoPic").val("");
$("#divUserLogo").show();
LogoName = "";
LogoExt = "";
base64Img = "";
}
= > UserLogo selected file is an image, it will be displayed in the <img>
element with the ID UserLogo
as a preview.
Declare three variable to store the image extension , image name , base64 string
var LogoName = "";
var LogoExt = "";
var base64Img = "";
🖼️ How It's Used to Show an Image
When this kind of string is used as the src
of an <img>
tag, the browser will decode the Base64 string and render the image directly—no file or URL needed.
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..." />
This will display the image right in the browser without loading it from a server.