1. 程式人生 > >使用Python生成Excel格式的圖片

使用Python生成Excel格式的圖片

之前曾看到過 一篇報道,說有個日本人利用Excel作畫。他把每個單元格填充上顏色,縮小顯示比例,就展現出一幅畫。記者採訪他,他說因為買不起正版的Photoshop,才委曲求全用Excel將就。

當時看著幾百乘幾百的單元格里,填滿眼花繚亂的的顏色,心想這得花多大的精力啊?

後來想想,要是用程式設計來實現,普通人幾分鐘之內也可以完成幾幅,甚至可以達到照片級,呵呵~

先看個效果圖,Excel格式的圖片,夠Geek吧。



用Python來實現,是很簡單的,我的平臺是:
Python 2.7.5;
PIL 1.1.7;
XlsxWriter 0.3.5;

需要說明的是,之所以選擇XlsxWriter,而不是常用的xlwt,是因為前者可以操作Excel2007版本的xlsx檔案。它擁有更多的行和列。

主要思路,就是使用PIL開啟圖片檔案,讀出每個畫素點的RGB值,再填充Excel檔案。

需要注意的是,Excel2007對於單元格樣式的種類也是有要求的,貌似最多65536種。因此有可能需要對顏色進行圓整。我也曾想使用PIL預先將圖片的顏色轉為65536色(16 bit),但是貌似PIL對65536色不太支援,所以只能出此下策。

# coding: utf-8

from PIL import Image
from xlsxwriter.workbook import Workbook

class ExcelPicture(object):
    FORMAT_CONSTRAINT = 65536
    
    def __init__(self, pic_file, ratio = 1.0):
        self.__pic_file = pic_file
        
        self.__ratio = ratio
        self.__zoomed_out = False
        
        self.__formats = dict()
        
        
    # 縮小圖片    
    def zoom_out(self, _img):
        _size = _img.size
        _img.thumbnail((int(_img.size[0] * self.__ratio), int(_img.size[1] * self.__ratio)))
        
        self.__zoomed_out = True
        
        
    # 對顏色進行圓整    
    def round_rgb(self, rgb, model):
        return tuple([int(round(x / model) * model) for x in rgb])
    
    
    # 查詢顏色樣式,去重    
    def get_format(self, color):
        _format = self.__formats.get(color, None)
        
        if _format is None:
            _format = self.__wb.add_format({'bg_color': color})
            self.__formats[color] = _format
            
        return _format
    
    
    # 操作流程
    def process(self, output_file = '_pic.xlsx', color_rounding = False, color_rounding_model = 5.0):
        # 建立xlsx檔案,並調整行列屬性
        self.__wb = Workbook(output_file)
        self.__sht = self.__wb.add_worksheet()
        self.__sht.set_default_row(height = 9)
        self.__sht.set_column(0, 5000, width = 1)
        
        # 開啟需要進行轉換的圖片
        _img = Image.open(self.__pic_file)
        print 'Picture filename:', self.__pic_file
        
        # 判斷是否需要縮小圖片尺寸
        if self.__ratio < 1: self.zoom_out(_img)
        
        # 遍歷每一個畫素點,並填充對應的顏色到對應的Excel單元格
        _size = _img.size
        print 'Picture size:', _size
        for (x, y) in [(x, y) for x in xrange(_size[0]) for y in xrange(_size[1])]:
            _clr = _img.getpixel((x, y))
            
            # 如果顏色種類過多,則需要將顏色圓整到近似的顏色上,以減少顏色種類
            if color_rounding: _clr = self.round_rgb(_clr, color_rounding_model)
            
            _color = '#%02X%02X%02X' % _clr
            self.__sht.write(y, x, '', self.get_format(_color))
        
        self.__wb.close()
        
        # 檢查顏色樣式種類是否超出限制,Excel2007對樣式數量有最大限制
        format_size = len(self.__formats.keys())
        if format_size >= ExcelPicture.FORMAT_CONSTRAINT:
            print 'Failed! Color size overflow: %s.' % format_size
        else:
            print 'Success!'
            print 'Color: %s' % format_size
            print 'Color_rounding:', color_rounding
            if color_rounding: print 'Color_rounding_model:', color_rounding_model
        
        
if __name__ == '__main__':
    r = ExcelPicture('b022_c.jpg', ratio = 0.5)
    r.process('b022_c.xlsx', color_rounding = True, color_rounding_model = 5.0)