Base64 turns file bytes into text a document can hold
Base64 maps every three bytes onto four characters from a 64-letter alphabet, so an image file can sit inside JSON, XML, or an HTML attribute. A data URL adds a media type in front of that text, which tells a parser what kind of image the bytes are. Turn the text back into a file with Base64 to image. After it is inside a tag, tidy the page in the HTML formatter.
The alphabet is A–Z, a–z, 0–9, plus, and slash. An equals sign at the end is padding. It is not a byte from the image.
What those characters actually encode
How three bytes become four Base64 characters
- Twenty-four bits are split into four indexes of six bits each.
- Each index picks one character from the 64-letter alphabet.
- A final group of one or two bytes is padded with = so the length is a multiple of four.
- The characters are ASCII text. The image bytes appear only after decoding.
What the prefix and the payload each mean in a data URL
- The scheme is data:.
- The media type is image/png, image/jpeg, image/gif, or image/webp.
- ;base64, marks the payload as Base64 rather than percent-encoded bytes.
- The text after the comma is the same payload as raw Base64. The prefix only names the type.
Why the payload is the whole file and not a decimal of each pixel
- A PNG signature, a JPEG start-of-image marker, a GIF header, and a WebP RIFF chunk travel with the bytes.
- Transparency, animation frames, and compression tables are inside that file.
- Decoding restores those bytes bit for bit. It does not rebuild a table of red, green, and blue numbers.
- A PNG and a JPEG of the same picture are different byte strings, so their Base64 differs too.
Why the text is about one third longer than the file
- Each character carries 6 bits, so four characters cover three bytes. The ratio is 4/3.
- A 300 KB JPEG is about 400 KB of text before the data URL prefix.
- The prefix adds a few dozen characters and does not change the payload.
- Text nested in a page is not a separate response, so it does not get its own cache entry the way an image URL does.
Where the text has to stand in for the file
An img src or a CSS url()
The whole data URL is the value: scheme, media type, and payload. A raw payload has no media type, so the characters alone do not say whether the file is a PNG or a JPEG. Rules around that image belong in the CSS formatter.
A JSON field that stores the picture apart from its type
The payload is the field value. The type is another field, or a header. Putting the data: prefix into a field that expects only the alphabet duplicates the type.