Home > Web Front-end > CSS Tutorial > How to Embed PNG Images in CSS Stylesheets Using Base64 Encoding?

How to Embed PNG Images in CSS Stylesheets Using Base64 Encoding?

Barbara Streisand
Release: 2024-10-30 07:37:28
Original
312 people have browsed it

How to Embed PNG Images in CSS Stylesheets Using Base64 Encoding?

Embedding PNG Images in CSS Stylesheets Using Base64 Encoding

To include PNG images in CSS stylesheets using data URIs, it's necessary to convert them to Base64 encoding. Here's how you can achieve this:

On macOS and Linux, you can use the following command line method:

base64 filepath > filepath.b64
Copy after login

Alternatively, you can use Python for a more versatile approach:

<code class="python">import base64

binary_fc = open(filepath, 'rb').read()
base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8')

ext = filepath.split('.')[-1]
dataurl = f'data:image/{ext};base64,{base64_utf8_str}'</code>
Copy after login

In this Python solution, the decode('utf-8') ensures compatibility with modern browsers, and the prefix data:image/{ext};base64, is essential for identifying the image format and encoding.

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