Home  >  Article  >  Web Front-end  >  How to Encode PNG Images in Base-64 for CSS Data-URIs on Mac or with Python?

How to Encode PNG Images in Base-64 for CSS Data-URIs on Mac or with Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 10:29:27642browse

How to Encode PNG Images in Base-64 for CSS Data-URIs on Mac or with Python?

Base-64 Encoding PNG Images for CSS Data-URIs

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:

Python Implementation:

<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 data:image/{ext};base64, prefix is necessary for specifying the image data type.
  • The decode('utf-8') step is essential to ensure the string is Unicode-compliant for proper display in CSS.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn