How to read a data URL

A data URL that declares image/png can hold just two bytes of text. Separate the header from the data, decode the bytes and check the file type before saving.

Split at the first comma

The first comma marks the start of the data. In this example text/plain identifies text, and ;base64 tells the reader how to decode SGk=. The result is Hi.

data:text/plain;base64,SGk=  →  Hi
data:,Hi%20there             →  Hi there

The header may also include a charset. When the media type is omitted entirely, the default is text/plain with US-ASCII. In the second example %20 represents a space. Give the inspector the whole URL so it can choose the decoding method.

Two ways to carry the same text

These two URLs both contain café in UTF-8. The first writes the two bytes of é as percent escapes. The second encodes all five bytes as Base64. Run both through the inspector and compare the byte count and the first bytes.

data:text/plain;charset=utf-8,caf%C3%A9
data:text/plain;charset=utf-8;base64,Y2Fmw6k=
HEX  →  63 61 66 C3 A9
data:,A%2CB%20C  →  A,B C

A comma inside the payload is data. In the last line %2C represents the comma and %20 the space in A,B C. Split the original URL at its first comma before decoding the payload.

Check the bytes before saving an image

The media type is supplied by whoever created the URL. In this example the header claims PNG while the decoded bytes 48 69 spell Hi. Compare those two bytes with the eight-byte signature of an actual PNG before choosing a file extension.

data:image/png;base64,SGk=  →  48 69
PNG  →  89 50 4E 47 0D 0A 1A 0A

Use the inspector for an unknown payload and check its reported bytes. When they really are an image, the image converter can recognize PNG, JPEG, GIF and WebP and choose the matching download extension.

Official sources