Python 之将小姐姐画在Excel上
源码:
1 from PIL import Image 2 import xlsxwriter 3 4 # 颜色转换函数 5 def color(value): 6 digit = list(map(str, range(10))) + list("ABCDEF") 7 if isinstance(value, tuple): 8 string = '#' 9 for i in value: 10 a1 = i // 16 11 a2 = i % 16 12 string += digit[a1] + digit[a2] 13 return string 14 elif isinstance(value, str): 15 a1 = digit.index(value[1]) * 16 + digit.index(value[2]) 16 a2 = digit.index(value[3]) * 16 + digit.index(value[4]) 17 a3 = digit.index(value[5]) * 16 + digit.index(value[6]) 18 return (a1, a2, a3) 19 # 路径 20 path = r'girl.jpg' 21 img = Image.open(path) 22 #img = img.resize((189, 152)) 23 # 转为rgb 24 imgL = img.convert("P").convert("RGB") 25 26 pix = imgL.load() 27 28 w, h = imgL.size 29 workbook = xlsxwriter.Workbook('picture.xlsx') # 新建excel表 30 31 worksheet = workbook.add_worksheet('sheet1') # 新建sheet(sheet的名称为"sheet1") 32 33 for j in range(w): 34 for i in range(h): 35 color_cell = color(pix[j, i]) 36 # 添加样式 37 sty = workbook.add_format({'bg_color': '{}'.format(color_cell) }) 38 # 写入 39 worksheet.write(i, j, '', sty) 40 # 设置行高 41 worksheet.set_row(i,1) 42 # 设置列宽 43 worksheet.set_column(0,w-1,0.4) 44 45 workbook.close()
图片:
效果图:
这是调整后行与列均为1像素的效果。