Question:
How can I convert a PNG image to base-64 encoded format for use as a data URI in a CSS stylesheet?
Unfortunately, this question cannot be resolved using a Unix command line solution.
Answer:
To convert a PNG image to base-64 encoded format in Python, follow these steps:
Example Code:
<code class="python">import base64 binary_fc = open(filepath, 'rb').read() # fc aka file_content base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8') ext = filepath.split('.')[-1] dataurl = f'data:image/{ext};base64,{base64_utf8_str}'</code>
Note:
Remember to include the necessary prefix data:image/{ext};base64, for the data URI to be valid.
The above is the detailed content of How to Convert a PNG Image to Base-64 Encoding for CSS Data URIs in Python?. For more information, please follow other related articles on the PHP Chinese website!