python自动将图片复刻到excel表格代码,将图像分割成一个个小块,复刻到excel表格内的小格子里,将小块的坐标和颜色对应填充到表格中。
from PIL import Image import openpyxl from openpyxl.styles import PatternFill import tkinter as tk from tkinter import filedialog def img_to_excel(image_path, excel_path): # 打开图像并缩放到较小的尺寸以适应Excel的单元格数量 img = Image.open(image_path).convert('RGB').resize((300, 300)) width, height = img.size pixels = img.load() # 创建新的Excel工作簿和工作表 wb = openpyxl.Workbook() ws = wb.active # 设置所有列的宽度 for i in range(width): ws.column_dimensions[openpyxl.utils.get_column_letter(i+1)].width = 2 for y in range(height): for x in range(width): r, g, b = pixels[x, y] # 创建颜色填充 fill = PatternFill(start_color=f'{r:02X}{g:02X}{b:02X}', end_color=f'{r:02X}{g:02X}{b:02X}', fill_type='solid') # 设置单元格的颜色 ws.cell(row=y+1, column=x+1).fill = fill # 保存到Excel文件 wb.save(excel_path) def main(): root = tk.Tk() root.withdraw() # 隐藏主窗口 # 弹出文件选择对话框让用户选择图片 image_path = filedialog.askopenfilename( title='选择图片', filetypes=[('Image Files', '*.png *.jpg *.jpeg *.bmp *.tif *.tiff *.gif')]) # 弹出文件保存对话框让用户选择Excel文件的保存路径 excel_path = filedialog.asksaveasfilename( title='保存Excel文件', filetypes=[('Excel Files', '*.xlsx')], defaultextension='.xlsx') # 将图片中的像素颜色信息保存到Excel文件 img_to_excel(image_path, excel_path) if __name__ == '__main__': main()