天天看點

【雜項】python将圖檔轉成Excel單元格顯示;Excel生成圖檔思路代碼實作運作結果

目錄

  • 思路
  • 代碼實作
  • 運作結果

用python做的小玩意,可以在Excel單元格填充顔色,所有像素組合成一張圖檔。

思路

  1. 讀取圖檔
  2. 擷取圖檔像素資訊
  3. 設定在Excel裡顯示的像素量。保留長寬資訊
  4. 縮放圖檔
  5. 活的縮放後圖檔每個像素點的顔色值
  6. 依次為表格添加顔色
  7. 設定表格行高列寬
  8. 儲存

代碼實作

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')
           

運作結果

原圖檔:

【雜項】python将圖檔轉成Excel單元格顯示;Excel生成圖檔思路代碼實作運作結果

輸出:

【雜項】python将圖檔轉成Excel單元格顯示;Excel生成圖檔思路代碼實作運作結果