有趣的Python:Excel作畫

前段時(shí)間看到一個(gè)新聞:日本74歲老人用Excel畫畫 栩栩如生!,的確很美,許多網(wǎng)友看了之后感嘆“我可能用了假的Excel”。

作為一個(gè)碼農(nóng),雖然缺少繪畫的藝術(shù)細(xì)胞,但特別擅長(zhǎng)用程序來(lái)處理數(shù)字化的信息。說(shuō)白了,excel也是一個(gè)數(shù)字化的文件嘛,那么從一個(gè)現(xiàn)有的圖片,讀取每個(gè)像素的顏色值,然后再填充到excel對(duì)應(yīng)單元格,不就完成了Excel作畫嗎?

所干就干,代碼如下:

from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Color
from PIL import Image

# 定義常量
IMAGE_FILE = 'starsky.jpg'  # 圖片的文件名
IMAGE_MAX_SIZE = 400  # 圖片長(zhǎng)邊像素的最大值,如果超出此值,將縮小圖片。

img = Image.open(IMAGE_FILE)
print('image\'s type is %s' % img.format)

# 修正圖片尺寸
img_width, img_height = img.size
print('image\'s size is (%s, %s)' % (img_width, img_height))
if img_width > IMAGE_MAX_SIZE:
    img_height = int(img_height * IMAGE_MAX_SIZE / img_width)
    img_width = IMAGE_MAX_SIZE

if img_height > IMAGE_MAX_SIZE:
    img_width = int(img_width * IMAGE_MAX_SIZE / img_height)
    img_height = IMAGE_MAX_SIZE

img.thumbnail((img_width, img_height))  # 縮小圖片尺寸
print('image\'s new size is (%s, %s)' % (img_width, img_height))

# 由于excel對(duì)單元格填充色有要求,所以用以下兩行代碼把圖片轉(zhuǎn)換為8位色值
img = img.convert('P')
img = img.convert('RGB')

pix = img.load()

workbook = Workbook()
worksheet = workbook.active
print('begin convert, please waiting...')

# 獲取每個(gè)像素的色值,并填充到單元格
for row in range(1, img_height):
    for col in range(1, img_width):
        cell = worksheet.cell(column=col, row=row)
        point = pix[col-1, row-1]
        color = "FF%02X%02X%02X" % (point[0], point[1], point[2])
        cell.fill = PatternFill(patternType='solid', fgColor=Color(rgb=color))
    worksheet.row_dimensions[row].height = 6

for col in range(1, img_width):
    worksheet.column_dimensions[get_column_letter(col)].width = 1

# 保存生成的excel文件
workbook.save(filename='output.xlsx')
print('Complete.')

下載了一副梵高的“星空”,然后執(zhí)行上面的程序

"C:\Program Files\Python36\python.exe"
image's type is JPEG
image's size is (658, 483)
image's new size is (400, 293)
begin convert, please waiting...
Complete.

打開生成的“output.xlsx”文件,效果截圖如下:


100%比例顯示下的馬賽克效果

縮小Excel的顯示比例查看全圖,效果如下:


縮小顯示比例的全圖效果

以上的實(shí)踐比較有趣,雖然暫時(shí)還沒有什么實(shí)用價(jià)值,但掌握了以下python知識(shí):

  • 用“PIL”庫(kù)讀取、處理圖片
  • 用“openpyxl”庫(kù)操作Excel文件

另外:

  1. 日本老爺子是原創(chuàng)作畫,的確佩服,博聞廣見,才能向高人學(xué)習(xí)、拓展思路;
  2. 擁有抽象思維,可以做到“用代碼實(shí)現(xiàn)所有重復(fù)性的信息化操作”。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容