Home >Web Front-end >CSS Tutorial >How to Embed Base64-Encoded PNG Images in CSS Data-URIs?

How to Embed Base64-Encoded PNG Images in CSS Data-URIs?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 06:02:02853browse

How to Embed Base64-Encoded PNG Images in CSS Data-URIs?

Embedding Base64-Encoded PNG Images in CSS Data-URIs

To embed a PNG image directly into a CSS file using a data-uri, it needs to be base-64 encoded. Here's how to do it:

Python Solution:

<code class="python">import base64

# Read the PNG file as binary
filepath = "path/to/image.png"
binary_fc = open(filepath, 'rb').read()

# Base-64 encode the binary data
base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8')

# Get the file extension
ext = filepath.split('.')[-1]

# Create the data-uri
dataurl = f'data:image/{ext};base64,{base64_utf8_str}'</code>

Notes:

  • The data-uri must include the image type and base64 prefix: data:image/{ext};base64,.
  • The decode('utf-8') step is necessary to work with certain browsers and encoders.

The above is the detailed content of How to Embed Base64-Encoded PNG Images in CSS Data-URIs?. 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