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

Linda Hamilton
Release: 2024-11-02 06:02:02
Original
808 people have browsed it

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

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!

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