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.
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.