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.
This program requires a file named "test.jpg" in the working directory—please create one or copy one before running it.
read()
will return a bytes object.string
by calling decode()
on it.string
literal. We specify the needed HTML and CSS.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'
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.