Home
Python
base64 Example (b64encode)
Updated Mar 21, 2024
Dot Net Perls
Base64. Many files contain binary data, and this data cannot be represented in plain text. But by converting it to base64, we can store the data within a string or text file.
Though it becomes larger, and thus loses efficiency, base64-encoded data can still be beneficial due to its portability. With the base64 module in Python, we can convert data to base64 encoding.
Example. This program requires a file named "test.jpg" in the working directory—please create one or copy one before running it.
Step 1 We read in the test.jpg file. We specify "rb" to read a binary file—this means read() will return a bytes object.
File
Step 2 We call b64encode to convert the bytes object into a encoded bytes object.
Step 3 For debugging purposes, we print the first 50 bytes of the encoded base64 bytes by using a Python slice.
Slice
Step 4 We convert the encoded base64 bytes object into an ASCII string by calling decode() on it.
bytes
Step 5 To create an HTML file with a data URI image, we use a format string literal. We specify the needed HTML and CSS.
format
Step 6 We write the example.html file which contains a base64-encoded image within a data URI, and then open it in a web browser.
import base64 # Step 1: read in the file. with open("test.jpg", "rb") as f: # Step 2: encode as base 64 with b64encode. encoded = base64.b64encode(f.read()) # Step 3: print first 50 bytes of the base 64 encoded file. print(encoded[0:50]) # Step 4: encode bytes to string. result = encoded.decode("ascii") # Step 5: create a data url in an html string. html = f"<html><body style=\"background:url(data:image/jpeg;base64,{result}\"></body></html>" # Step 6: write to example html file. with open("example.html", "w") as f2: f2.write(html)
b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBAQFBAYFBQYJBg'
Summary. Python is a batteries-included language, which means useful features like base64-encoding are built in. With just a module import and a method call, we can get converted base64 data.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 21, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen