import os
import base64
from mimetypes import guess_type
deflocal_image_to_data_url(image_path):# Guess the MIME type of the image based on the file extension
mime_type, _ = guess_type(image_path)if mime_type isNone:
mime_type ='application/octet-stream'# Default MIME type if none is found# Read and encode the image filewithopen(image_path,"rb")as image_file:
base64_encoded_data = base64.b64encode(image_file.read()).decode('utf-8')# Construct the data URLreturnf"data:{mime_type};base64,{base64_encoded_data}"defget_image_message(img_path):def_get_template(image_path):print('文件路径为:'+ image_path)
url = local_image_to_data_url(image_path)return{"type":"image_url","image_url":{"url": url
},}ifnot os.path.exists(img_path):print(f"Error: Path {img_path} does not exist.")return
image_extensions =['.png','.jpg','.jpeg']
image_message =[]# 判断传入的是一个file还是folderif os.path.isfile(img_path):
image_url = _get_template(img_path)
image_message.append(image_url)elif os.path.isdir(img_path):for f in os.listdir(img_path):ifany(f.lower().endswith(ext)for ext in image_extensions):
image_url = _get_template(os.path.join(img_path, f))
image_message.append(image_url)else:print("错误!请检测传入的图片文件夹目录结构。")return image_message
if __name__ =='__main__':
img_path ="img/temp/"
user_image_message = get_image_message(img_path)