用python做的小玩意,可以在Excel单元格填充颜色,所有像素组合成一张图片。
思路
- 读取图片
- 获取图片像素信息
- 设定在Excel里显示的像素量。保留长宽信息
- 缩放图片
- 活的缩放后图片每个像素点的颜色值
- 依次为表格添加颜色
- 设置表格行高列宽
- 保存
代码实现
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Color
from PIL import Image
import os
# 设置路径
path='D:/desktop/'
os.chdir(path)
# 打开表格
workbook = Workbook()
worksheet = workbook.active
# 读取照片
im = Image.open("longjs.jpg")
im_width = im.size[0]
im_height = im.size[1]
# 将照片适度缩放,像素太多影响生成
target_height = 100
target_width = int(target_height*im_width/im_height)
# 实行缩放
im_resize = im.resize((target_width, target_height),Image.Resampling.LANCZOS)
# 给每个表格填充颜色
pix = im_resize.load()
for row in range(1, target_height):
for col in range(1, target_width):
cell = worksheet.cell(column=col, row=row)
pixpoint = pix[col - 1, row - 1]
pixColor = "FF%02X%02X%02X" % (pixpoint[0], pixpoint[1], pixpoint[2])
fill = PatternFill(patternType='solid',fgColor=Color(rgb=pixColor))
cell.fill = fill
# 设置行高
worksheet.row_dimensions[row].height = 6
# 设置列宽
for col in range(1, target_width):
worksheet.column_dimensions[get_column_letter(col)].width = 1
# 保存结果
workbook.save(filename='longjs.xlsx')
运行结果
原图片:
输出: