Python代碼,將圖片轉為了Excel


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文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM