Created
March 30, 2022 22:44
-
-
Save du-song/741997588d12c5953b207c5d233fe50e to your computer and use it in GitHub Desktop.
Convert image to Excel file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xlsxwriter | |
from PIL import Image | |
import sys | |
def rgb2hex(r, g, b): | |
return '#{:02x}{:02x}{:02x}'.format(r, g, b) | |
if len(sys.argv) != 3: | |
print(sys.argv[0] + ' place.png place.xlsx') | |
exit() | |
im = Image.open(sys.argv[1]) | |
px = im.load() | |
wb = xlsxwriter.Workbook(sys.argv[2]) | |
ws = wb.add_worksheet() | |
fmts = {} | |
for y in range(0, im.height): | |
for x in range(0, im.width): | |
r, g, b, _ = px[x, y] | |
c = rgb2hex(r, g, b) | |
if c in fmts: | |
f = fmts[c] | |
else: | |
f = wb.add_format() | |
f.set_bg_color(c) | |
if r + g + b < 128 * 3: | |
f.set_font_color('white') | |
fmts[c] = f | |
ws.write(y + 1, x + 1, ' ', f) | |
wb.close() | |
print('Done.') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Pillow | |
XlsxWriter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment