Embedding PNG Images in CSS Stylesheets Using Base64 Encoding
To include PNG images in CSS stylesheets using data URIs, it's necessary to convert them to Base64 encoding. Here's how you can achieve this:
On macOS and Linux, you can use the following command line method:
base64 filepath > filepath.b64
Alternatively, you can use Python for a more versatile approach:
<code class="python">import base64 binary_fc = open(filepath, 'rb').read() base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8') ext = filepath.split('.')[-1] dataurl = f'data:image/{ext};base64,{base64_utf8_str}'</code>
In this Python solution, the decode('utf-8') ensures compatibility with modern browsers, and the prefix data:image/{ext};base64, is essential for identifying the image format and encoding.
The above is the detailed content of How to Embed PNG Images in CSS Stylesheets Using Base64 Encoding?. For more information, please follow other related articles on the PHP Chinese website!