先看個效果圖,Excel格式的圖片,夠Geek吧。 python
用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('cw.jpg', ratio = 0.5) r.process('cw.xlsx', color_rounding = True, color_rounding_model = 5.0)