Python代码将图片转为Excel

通过Python脚本实现将一张图片(horse.jpg)转换为Excel文件,每个单元格的背景色对应图片的一个像素点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写了一小段Python代码,将图片转为了Excel,纯属娱乐。原理很简单,就是将图片每个像素的颜色填充到Excel对应的单元格中。

原图(horse.jpg):




转换后的Excel文档(horse.jpg.xlsx):




转换后的截图:




放大截图:




代码如下,就15行:

[python]  view plain  copy
  1. from PIL import Image  
  2. import openpyxl  
  3. from openpyxl.styles import PatternFill, Fill  
  4.   
  5. imageFileName = 'horse.jpg' #图片文件名  
  6. image = Image.open(imageFileName) #打开图片  
  7. wb = openpyxl.Workbook() #创建Excel  
  8. sheet = wb.create_sheet(imageFileName) #创建sheet  
  9. imgW, imgH = image.size #获取图片大小  
  10. for w in range(imgW):  
  11.     for h in range(imgH):  
  12.         #将每个像素的颜色填充到对应cell的背景色中  
  13.         rgba = image.getpixel((w,h))  
  14.         colorHex = hex(rgba[0])[2:].zfill(2) + hex(rgba[1])[2:].zfill(2) + hex(rgba[2])[2:].zfill(2)  
  15.         fill = PatternFill(fill_type = 'solid', start_color=colorHex, end_color=colorHex)  
  16.         sheet.cell(row = h + 1, column = w + 1).fill = fill  
  17. wb.save(imageFileName + '.xlsx'#保存xlsx文件  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值