Home >Web Front-end >CSS Tutorial >How to Convert a PNG Image to Base-64 Encoding for CSS Data URIs in Python?

How to Convert a PNG Image to Base-64 Encoding for CSS Data URIs in Python?

DDD
DDDOriginal
2024-10-30 12:32:38334browse

How to Convert a PNG Image to Base-64 Encoding for CSS Data URIs in Python?

Embedding PNG Images in CSS Using Base-64 Encoding

Question:

How can I convert a PNG image to base-64 encoded format for use as a data URI in a CSS stylesheet?

Unix Command Line Solution:

Unfortunately, this question cannot be resolved using a Unix command line solution.

Python-Based Solution:

Answer:

To convert a PNG image to base-64 encoded format in Python, follow these steps:

  1. Import the base64 module.
  2. Read the binary contents of the PNG file using open(filepath, 'rb').read().
  3. Encode the binary data using base64.b64encode(binary_fc).
  4. Decode the base-64 encoded data to UTF-8 using decode('utf-8').
  5. Determine the file extension of the PNG image.
  6. Create a data URI using the following format: data:image/{ext};base64,{base64_utf8_str}.

Example Code:

<code class="python">import base64

binary_fc        = open(filepath, 'rb').read()  # fc aka file_content
base64_utf8_str   = base64.b64encode(binary_fc).decode('utf-8')
ext              = filepath.split('.')[-1]
dataurl          = f'data:image/{ext};base64,{base64_utf8_str}'</code>

Note:

Remember to include the necessary prefix data:image/{ext};base64, for the data URI to be valid.

The above is the detailed content of How to Convert a PNG Image to Base-64 Encoding for CSS Data URIs in 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