以下是几种实现图片转Base64的方法:
方法一:使用Python内置的base64模块
- import base64
-
- def image_to_base64(file_path):
- with open(file_path, "rb") as image_file:
- encoded_string = base64.b64encode(image_file.read())
- return encoded_string.decode("utf-8")
方法二:使用Pillow库(Python Imaging Library的更新版)
- from PIL import Image
- import io
- import base64
-
- def image_to_base64(file_path):
- image = Image.open(file_path)
- byte_stream = io.BytesIO()
- image.save(byte_stream, format="PNG") # 可根据需要修改保存格式
- encoded_string = base64.b64encode(byte_stream.getvalue())
- return encoded_string.decode("utf-8")
方法三:使用OpenCV库
- import cv2
- import base64
-
- def image_to_base64(file_path):
- image = cv2.imread(file_path)
- _, encoded_image = cv2.imencode(".png", image) # 可根据需要修改保存格式
- encoded_string = base64.b64encode(encoded_image)
- return encoded_string.decode("utf-8")
这些方法都能将指定路径的图片文件转换为Base64编码字符串。方法一是使用Python内置的base64模块,方法二和方法三则依赖于Pillow库和OpenCV库,可根据自己的环境和需求进行选择使用。