源码:
from PIL import Image
import xlsxwriter
def color(value):
digit = list(map(str, range(10))) + list("ABCDEF")
if isinstance(value, tuple):
string = '#'
for i in value:
a1 = i // 16
a2 = i % 16
string += digit[a1] + digit[a2]
return string
elif isinstance(value, str):
a1 = digit.index(value[1]) * 16 + digit.index(value[2])
a2 = digit.index(value[3]) * 16 + digit.index(value[4])
a3 = digit.index(value[5]) * 16 + digit.index(value[6])
return (a1, a2, a3)
path = r'girl.jpg'
img = Image.open(path)
imgL = img.convert("P").convert("RGB")
pix = imgL.load()
w, h = imgL.size
workbook = xlsxwriter.Workbook('picture.xlsx')
worksheet = workbook.add_worksheet('sheet1')
for j in range(w):
for i in range(h):
color_cell = color(pix[j, i])
sty = workbook.add_format({
'bg_color': '{}'.format(color_cell) })
worksheet.write(i, j, '', sty)
worksheet.set_row(i,1)
worksheet.set_column(0,w-1,0.4)
workbook.close()
图片:
效果图:
这是调整后行与列均为1像素的效果。