
在 CSS Data-URI 中嵌入 Base64 编码的 PNG 图像
使用 data-uri 将 PNG 图像直接嵌入到 CSS 文件中,它需要进行 base-64 编码。操作方法如下:
Python 解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <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>
|
登录后复制
注释:
- 数据- uri 必须包含图像类型和 base64 前缀:data:image/{ext};base64,.
- decode('utf-8') 步骤是与某些浏览器和编码器配合使用所必需的。
以上是如何在 CSS 数据 URI 中嵌入 Base64 编码的 PNG 图像?的详细内容。更多信息请关注PHP中文网其他相关文章!