Home > Article > Web Front-end > How to Encode PNG Images in Base-64 for CSS Data-URIs on Mac or with Python?
Problem:
Incorporating images into CSS using data-URIs requires converting the image to Base-64 format. How can this be achieved on a Mac or using Python?
Solution:
<code class="python">import base64 # Open the PNG file and read its binary contents binary_file_content = open(filepath, 'rb').read() # Encode the binary contents to Base-64 and decode it as UTF-8 base64_utf8_str = base64.b64encode(binary_file_content).decode('utf-8') # Extract the file extension ext = filepath.split('.')[-1] # Format the complete data-URI dataurl = f'data:image/{ext};base64,{base64_utf8_str}'</code>
Notes:
The above is the detailed content of How to Encode PNG Images in Base-64 for CSS Data-URIs on Mac or with Python?. For more information, please follow other related articles on the PHP Chinese website!