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

Linda Hamilton
Release: 2024-10-30 10:29:27
Original
658 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!