加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python代码,将图片转为了Excel

发布时间:2020-12-20 10:56:45 所属栏目:Python 来源:网络整理
导读:Python代码,将图片转为了Excel 原理很简单,就是将图片每个像素的颜色填充到Excel对应的单元格中。 from PIL import Imageimport openpyxlfrom openpyxl.styles import PatternFill,FillimageFileName = 'horse.jpg' #图片文件名image = Image.open(imageFi

Python代码,将图片转为了Excel
原理很简单,就是将图片每个像素的颜色填充到Excel对应的单元格中。

from PIL import Image
import openpyxl
from openpyxl.styles import PatternFill,Fill
imageFileName = 'horse.jpg' #图片文件名
image = Image.open(imageFileName) #打开图片
wb = openpyxl.Workbook() #创建Excel
sheet = wb.create_sheet(imageFileName) #创建sheet
imgW,imgH = image.size #获取图片大小
for w in range(imgW):
    for h in range(imgH):
        #将每个像素的颜色填充到对应cell的背景色中
        rgba = image.getpixel((w,h))
        colorHex = hex(rgba[0])[2:].zfill(2) + hex(rgba[1])[2:].zfill(2) + hex(rgba[2])[2:].zfill(2)
        fill = PatternFill(fill_type = 'solid',start_color=colorHex,end_color=colorHex)
        sheet.cell(row = h + 1,column = w + 1).fill = fill
wb.save(imageFileName + '.xlsx') #保存xlsx文件

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读