import base64
def image_to_base64(image_path):
"""
将图片文件转换为Base64编码的字符串。
参数:
image_path (str): 图片文件的路径。
返回:
str: Base64编码的字符串。
"""
try:
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return encoded_string
except Exception as e:
print(f"Error: {e}")
return None
# 示例用法
image_path = 'example.jpg' # 替换为你的图片路径
base64_string = image_to_base64(image_path)
if base64_string:
print(base64_string)
base64 模块来处理Base64编码。image_to_base64 函数接收一个图片文件路径作为参数。rb) 打开图片文件,并读取其内容。base64.b64encode 方法将图片的二进制数据编码为Base64格式,然后使用 decode('utf-8') 将其转换为字符串。None。上一篇:python dict.get
下一篇:python tuple类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站