Python 居然可以在 Excel 中画画你知道吗
作者:迢迢x 时间:2023-09-14 23:13:06
导语:
用 Python 读取图片的像素值,然后输出到 Excel 表格中,最终形成一幅像素画,也就是电子版的十字绣了。
基本思路
实现这个需求的基本思路是读取这张图片每一个像素的色彩值,然后给 excel 里的每一个单元格填充上颜色。既然要读取图片,那就需要用到 Pillow 库,操作 Excel 需要用到 openpyxl 库,先把这两个库安装好。
pip3 install openpyxl
pip3 install Pillow
色值转换
从图片读取的像素块色值是 RGB 值,而 openpyxl 向 Excel cell 内填充颜色是十六进制色值,因此咱们先写一个 RGB 和十六进制色值转换的一个函数。
def rgb_to_hex(rgb):
rgb = rgb.split(',')
color = ''
for i in RGB:
num = int(i)
color += str(hex(num))[-2:].replace('x', '0').upper()
return color
excel 的单元格默认是长方形,修改为正方形才不会使图片变形
if h == 1:
_w = cell.column
_h = cell.col_idx
# 调整列宽
worksheet.column_dimensions[_w].width = 1
# 调整行高
worksheet.row_dimensions[h].height = 6
这里用到了双重for循环,外层是`width`,里层是`height`,是一列一列的填充颜色,因此判断`if h == 1`,避免多次调整列宽。
图片转换
有了色值转换函数,接下来要做的操作就是逐行读取图片的 RGB 色值,之后将 RGB 色值转换为十六进制色值填充到 Excel 的 cell 中即可。
def img2excel(img_path, excel_path):
img_src = Image.open(img_path)
# 图片宽高
img_width = img_src.size[0]
img_height = img_src.size[1]
str_strlist = img_src.load()
wb = openpyxl.Workbook()
wb.save(excel_path)
wb = openpyxl.load_workbook(excel_path)
cell_width, cell_height = 1.0, 1.0
sheet = wb["Sheet"]
for w in range(img_width):
for h in range(img_height):
data = str_strlist[w, h]
color = str(data).replace("(", "").replace(")", "")
color = rgb_to_hex(color)
# 设置填充颜色为 color
fille = PatternFill("solid", fgColor=color)
sheet.cell(h + 1, w + 1).fill = fille
for i in range(1, sheet.max_row + 1):
sheet.row_dimensions[i].height = cell_height
for i in range(1, sheet.max_column + 1):
sheet.column_dimensions[get_column_letter(i)].width = cell_width
wb.save(excel_path)
img_src.close()
最后再来个入口函数,就大功告成啦~
if __name__ == '__main__':
img_path = '/Users/xyz/Documents/tmp/03.png'
excel_path = '/Users/xyz/Documents/tmp/3.xlsx'
img2excel(img_path, excel_path)
惊艳时刻
激动的心,颤抖的手,来看下最终效果咋样。
怎么样是不是觉得有那么一丝丝韵味呢...
来源:https://blog.csdn.net/a55656aq/article/details/122579220
标签:Python,Excel,画画,绘图
0
投稿
猜你喜欢
python3 下载网络图片代码实例
2021-11-21 01:11:40
基于事件冒泡、事件捕获和事件委托详解
2024-04-28 09:43:33
详解MySQL双活同步复制四种解决方案
2024-01-13 04:39:47
详解MySql存储过程参数的入门使用
2024-01-25 23:24:06
vue2.0+vue-dplayer实现hls播放的示例
2024-05-29 22:46:56
Ubuntu下使用Python实现游戏制作中的切分图片功能
2021-02-22 22:55:53
python爬虫之爬取百度翻译
2022-04-03 19:30:45
Python selenium 父子、兄弟、相邻节点定位方式详解
2023-07-03 06:19:09
IE下绝对定位的元素不能响应鼠标的bug修正
2008-09-10 13:03:00
python实现将多个文件分配到多个文件夹的方法
2023-04-13 20:48:46
Python海龟绘图之绘制趣味简笔画
2023-03-13 09:09:40
python中列表元素连接方法join用法实例
2023-01-20 17:49:31
anaconda3安装及jupyter环境配置全教程
2021-03-26 07:45:07
微软的jQuery国际化插件
2010-07-02 12:46:00
XHTML1.0规范:您是否为img图片标签赋予alt属性
2009-09-21 11:11:00
SQL Server提示"选定的用户拥有对象,所以无法除去该用户”
2024-01-22 03:35:05
如何让利用Python+AI使静态图片动起来
2022-06-06 08:15:31
深入理解MySQL事务的4种隔离级别
2024-01-21 09:52:40
MySQL的命令行提示符及其表达的意思
2008-03-17 13:34:00
Python+decimal完成精度计算的示例详解
2022-09-18 11:07:35