"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Encode PNG Images as Base64 for CSS Data URIs?

How to Encode PNG Images as Base64 for CSS Data URIs?

Published on 2024-11-06
Browse:404

How to Encode PNG Images as Base64 for CSS Data URIs?

Using Base64 Encoding for PNG Images in CSS Data URIs

In order to embed PNG images into CSS stylesheets using data URIs, the PNG data must first be encoded into Base64 format. This technique allows external image files to be included directly within the stylesheet.

Unix Command-Line Solution:

base64 -i /path/to/image.png

This command will output the Base64-encoded PNG data.

Python Solution:

import base64

with open("/path/to/image.png", "rb") as f:
    binary_data = f.read()

base64_data = base64.b64encode(binary_data).decode("utf-8")
ext = "png"

data_uri = f"data:image/{ext};base64,{base64_data}"

print(data_uri)

This Python script reads the PNG file in binary mode, converts it to Base64, and then constructs the data URI, including the appropriate MIME type and extension.

Additional Notes:

  • Ensure the image's extension is included in the data URI after the MIME type, e.g., "data:image/png;base64".
  • Use the "decode('utf-8')" method in Python to handle any potential Unicode-related issues.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3