Home
Map
base64 Example (b64encode)Use the base64 module to convert binary data to base-64 encoded data, and create data URI images with base64.
Python
This page was last reviewed on Mar 21, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 21, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.