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:
<code class="python">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)</code>
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:
The above is the detailed content of How to Encode PNG Images as Base64 for CSS Data URIs?. For more information, please follow other related articles on the PHP Chinese website!