python数据写入表格生成图片_python带表格图片生成封装
#!/usr/bin/python3#-*- coding: utf-8 -*-## author:qianqiu
from prettytable importPrettyTablefrom PIL importImage, ImageDraw, ImageFontdef create_table_img(data,img_name, **kwargs):'''img_name 圖片名稱 'D:/project/pythonwork/12306/t.png' 或 t.png
data 表格內(nèi)容,首行為表頭部
table_title 表格標(biāo)題
line_height 底部描述行高
font 默認(rèn)字體路徑
default_font_size 默認(rèn)字體大小
default_background_color 圖片背景底色
table_top_heght 設(shè)置表格頂部留白高度
table_botton_heght 設(shè)置表格頂部留白高度
describe 底部描述文字'''space= 20 ## 表格邊距
#生成圖片-------------------------------
### 底部描述行高
if 'line_height' not inkwargs:
line_height= 4
else:
line_height= kwargs['line_height']### 默認(rèn)字體
if 'font' not inkwargs:
kwargs['font'] =None### 默認(rèn)字體大小
if 'default_font_size' not inkwargs:
kwargs['default_font_size'] = 15
### 默認(rèn)表標(biāo)題字體大小
if 'table_title_font_size' not inkwargs:
kwargs['table_title_font_size'] = 22
### 圖片背景底色
if 'default_background_color' not inkwargs:
kwargs['default_background_color'] = (255,255,255,255)### 設(shè)置表格頂部留白高度
if 'table_top_heght' not inkwargs:
kwargs['table_top_heght'] = kwargs['table_title_font_size'] + space + int(kwargs['table_title_font_size']/2)## 底部描述文字
if 'describe' inkwargs:
describe_len= len(kwargs['describe'])else:
describe_len=0### 設(shè)置表格底部留白高度
if 'table_botton_heght' not inkwargs:
kwargs['table_botton_heght'] = describe_len * kwargs['default_font_size'] +space### 圖片后綴
if 'img_type' not inkwargs:
kwargs['img_type'] = 'PNG'
### 默認(rèn)字體及字體大小
font = ImageFont.truetype(kwargs['font'], kwargs['default_font_size'], encoding='utf-8')
font2= ImageFont.truetype(kwargs['font'], kwargs['table_title_font_size'], encoding='utf-8')## Image模塊創(chuàng)建一個(gè)圖片對(duì)象
im = Image.new('RGB',(10, 10),kwargs['default_background_color'])## ImageDraw向圖片中進(jìn)行操作,寫入文字或者插入線條都可以
draw =ImageDraw.Draw(im)#創(chuàng)建表格---------------------------------
tab = PrettyTable(border=True, header=True, header_style = 'title')## 第一行設(shè)置為表頭
tab.field_names =data.pop(0)for row indata:
tab.add_row(row)
tab_info=str(tab)## 根據(jù)插入圖片中的文字內(nèi)容和字體信息,來(lái)確定圖片的最終大小
img_size = draw.multiline_textsize(tab_info, font=font)
img_width= img_size[0]+space*2table_height= img_size[1]+space*2img_height= table_height + kwargs['table_botton_heght'] + kwargs['table_top_heght']
im_new=im.resize((img_width, img_height))deldrawdelim
draw= ImageDraw.Draw(im_new, 'RGB')
draw.multiline_text((space,kwargs['table_top_heght']), tab_info + '\n\n', fill=(0,0,0), font=font)### 表標(biāo)題--------------------------
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python数据写入表格生成图片_python带表格图片生成封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python turtle画彩虹的代码_
- 下一篇: Simply NUC 预告最强 4*4