Python 读取Excel中的图片并且保存到本地
1 import base64 2 import os 3 import zipfile 4 5 import matplotlib.pyplot as plt 6 from openpyxl import load_workbook 7 8 """ 9 下载Excel中的图片保存到本地 10 """ 11 12 13 def download_excel_image_save_local(): 14 wb = load_workbook('Image.xlsx') 15 ws = wb.active 16 print(ws) 17 output_dir = 'output_image' 18 if not os.path.exists(output_dir): 19 os.makedirs(output_dir) 20 21 with zipfile.ZipFile('Image.xlsx', 'r') as zip_ref: 22 for zip_info in zip_ref.infolist(): 23 if zip_info.filename.endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): 24 img_path = os.path.join(output_dir, os.path.basename(zip_info.filename)) 25 with zip_ref.open(zip_info) as img_file, open(img_path, 'wb') as out_file: 26 out_file.write(img_file.read()) 27 28 29 # 图片转Base64 30 def image_to_base64(file_path): 31 with open(file_path, "rb") as image_file: 32 str_encoded = base64.b64encode(image_file.read()) 33 return str_encoded.decode("utf-8") 34 35 36 # 读取文件夹里的图片 37 def read_image(folder_path): 38 for filename in os.listdir(folder_path): 39 print(filename) 40 if filename.endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): 41 img_path = os.path.join(folder_path, filename) 42 image = plt.imread(img_path) 43 img_base = image_to_base64(img_path) 44 print(img_base) 45 46 47 if __name__ == '__main__': 48 download_excel_image_save_local() 49 read_image("output_image")
执行结果: