Using Base64 Encoding for PNG Images in CSS Data URIs
In order to embed PNG images into CSS stylesheets using data URIs, the PNG data must first be encoded into Base64 format. This technique allows external image files to be included directly within the stylesheet.
Unix Command-Line Solution:
base64 -i /path/to/image.png
This command will output the Base64-encoded PNG data.
Python Solution:
import base64
with open("/path/to/image.png", "rb") as f:
binary_data = f.read()
base64_data = base64.b64encode(binary_data).decode("utf-8")
ext = "png"
data_uri = f"data:image/{ext};base64,{base64_data}"
print(data_uri)
This Python script reads the PNG file in binary mode, converts it to Base64, and then constructs the data URI, including the appropriate MIME type and extension.
Additional Notes:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3