目的:学习通过python的PIL库来做图片的绘制,帮助熟悉Image,ImageDraw,ImageFont的使用

第一部分,需要用到的函数封装

1、取星期几:

days=[ '星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期日']
def WeekDayName(day=datetime.datetime.weekday(datetime.datetime.now())):return days[day]

2、从文本文件中加载值日人员名单

文件记录格下如下:

D1=张三|李四|王麻子

说明,D代表单周(双周的话,我这里用的是“S"),1表现星期1,等于后面就是人员名单,通过”|“来分割

def LoadContents(DutyFile):SMaxCount = 0DMaxCount = 0if(os.path.exists(DutyFile)):with open(DutyFile, encoding="utf8") as f:for line in f.readlines():line = line.replace('\n','').encode('utf-8').decode('utf-8-sig')if line !='' and line != None and line[0]!='#':tmp = line.split("=")key = tmp[0]value = tmp[1]if key == 'title':self.Caption = valueelse:values = value.split('|')self.Students[key] = valuesif key[0] == 'D':DMaxCount = len(values) if DMaxCount< len(values) else DMaxCountelif key[0] =='S':SMaxCount = len(values) if SMaxCount< len(values) else SMaxCount#print(self.Students)return SMaxCount,DMaxCount

这里返了两个值,代表单双周中,人数最多的一例。这里主要是文件的读写,没有什么特别的地方。

3、绘制字符串信息,这里为了美观,我把所有的文字都居中显示了

    def DrawText(self,xy,text,font,color,draw):x = xy[0] #起点坐标xy = xy[1] #起点坐标Yw = xy[2] #宽h = xy[3] #高text_size = draw.textsize(text,font)x1 = x+(w / 2) - (text_size[0] / 2)y1 = y+(h / 2) - (text_size[1] / 2)draw.ink =  color       draw.text((x1,y1), text, fill=None, font = font)

4、然后就是画图了,具体看代码

 def Draw(self):#1、加载值日人员数据SMaxCount,DMaxCount=self.__LoadContents() #2、计算需要的数据weekNo = self.__CalcWeekNum()iweekday = datetime.datetime.weekday(datetime.datetime.now()) weekdayName = self.__WeekDayName()IfSingleWeek = True if weekNo % 2 == 1 else Falsered = 255 + 0 * 256 + 0 * 256 * 256orange = 255 + 165 * 256 + 0 * 256 * 256maroon =128+0*255+ 0* 256 * 256#3、开始画图Width = 770Height = 580bckcolor = (255,255,255)icol = DMaxCount + SMaxCountcols = icol + 2 + 1  #单周行数+又周行数+2标题+1表头colHeight = int( (Height - 4) / cols)rowWidth = int((Width - 4) / 6)#3.1标题img =  Image.new('RGB',size=(Width,Height),color=bckcolor)draw = ImageDraw.Draw(img)# 计算文字居中的位置font = ImageFont.truetype(self.CaptionFont, self.CaptionFontSize)self.__DrawText((2,2,Width,colHeight),self.Caption,font,red,draw)#副标题font = ImageFont.truetype(self.Font, self.FontSize)text = '{0}年{1}月{2}日  {3} 第{4}周'.format(self.CurrentDay.year,self.CurrentDay.month,self.CurrentDay.day, weekdayName,to_chinese(weekNo))self.__DrawText((2,colHeight,rowWidth*2.5,colHeight),text,font,0,draw)#3.2画表格irow = 5+1wtd = rowWidth * irow + 2;for i in range(0,icol+2):if i <2 or i== DMaxCount+1 or i == icol+1:draw.line((2,colHeight*(i+2) ,wtd, colHeight * (i + 2)),self.BroderColor, width=self.BroderLine)else:draw.line((2 + rowWidth,colHeight*(i+2), wtd, colHeight * (i + 2)),self.BroderColor, width=self.BroderLine)hgt = colHeight * (icol + 3);for i in range(0,irow+2):draw.line((2 + rowWidth * i, colHeight * 2, 2 + rowWidth * i, hgt),self.BroderColor,width=self.BroderLine)    draw.line( (2, colHeight * 2, rowWidth, colHeight * 3),self.BroderColor,width=self.BroderLine)#3.3画表头GridX = 2;GridY = colHeight * 2 + 2;self.__DrawText((GridX, GridY + colHeight / 2, rowWidth / 2, colHeight / 2),"周数",font,maroon,draw)    self.__DrawText((GridX + rowWidth / 2, GridY, rowWidth / 2, colHeight / 2),"星期",font,maroon,draw) font = ImageFont.truetype(self.Font, self.FontSize+6)for i in range(0,5):self.__DrawText((GridX + rowWidth * (i+1), GridY + colHeight * 0, rowWidth, colHeight),days[i],font,maroon,draw)  self.__DrawText((GridX, GridY + colHeight * 1, rowWidth, colHeight * DMaxCount),"单周",font,maroon,draw)    self.__DrawText((GridX, GridY + colHeight * (DMaxCount+1), rowWidth, colHeight * SMaxCount),"双周",font,maroon,draw)  #3.4画内容x0 = GridX + rowWidth;y0 = GridY + colHeight;for key,value in self.Students.items():weekflag = key[0]weekday = int(key[1])xoff,yoff = 0,0 fclr = self.FontColorif(weekflag== 'D'): #单周x0+colHeight, y0 + i * colHeight, rowWidth-colHeight, colHeightxoff = rowWidth * (weekday -1)yoff = 0if IfSingleWeek and iweekday+1 == weekday:fclr = redelif(weekflag =='S'):#双周xoff = rowWidth * (weekday -1)yoff = colHeight* DMaxCount if not IfSingleWeek and iweekday+1 == weekday:fclr = redfont = ImageFont.truetype(self.Font, self.FontSize)for i in range(0,len(value)):if fclr== red:txt = '※ '+value[i]else:txt = value[i]self.__DrawText((x0+xoff,y0+yoff+colHeight*i,rowWidth, colHeight),txt,font,fclr,draw) img.save("d:\zr.bmp", 'bmp', quality = 100)        img.show()del draw

这里需要注意,图片保存的时候,我这里用的BMP格式,因为JPG格式会导致图片失真,不清楚。

最后,把完整的代码送给大家。

from PIL import Image,ImageDraw,ImageFont
import datetime
import osdays=[ '星期一', '星期二', '星期三', '星期四', '星期五', '星期六','星期日']
class DutyTable:titleCount = 2cols = 10rows = 5#标题属性Caption = '值日表'CaptionFont = r'fonts\SIMLI.TTF'CaptionColor = (0,0,0)CaptionFontSize = 30#字体属性Font = 'fonts\simsun.ttc'FontSize = 20FontColor = 0#边框属性BroderLine = 2BroderColor = "Orange"colHeight = 0rowWidth = 0#第一天,因为学校周数是按学期来计算的,和一年中的第几周不一样FirstDay = datetime.date(2018,2,26)#当天CurrentDay = datetime.date.today()DutyFile = r'C:\Users\cdzq-xg\source\DutyTable\DutyTable\bin\Debug\contents.dat'Students = {}#计算第几周def __CalcWeekNum(self):return int(self.CurrentDay.__sub__(self.FirstDay).days/7)+1def __WeekDayName(self,day=datetime.datetime.weekday(datetime.datetime.now())):return days[day]def __LoadContents(self):SMaxCount = 0DMaxCount = 0if(os.path.exists(self.DutyFile)):with open(self.DutyFile, encoding="utf8") as f:for line in f.readlines():line = line.replace('\n','').encode('utf-8').decode('utf-8-sig')if line !='' and line != None and line[0]!='#':tmp = line.split("=")key = tmp[0]value = tmp[1]if key == 'title':self.Caption = valueelse:values = value.split('|')self.Students[key] = valuesif key[0] == 'D':DMaxCount = len(values) if DMaxCount< len(values) else DMaxCountelif key[0] =='S':SMaxCount = len(values) if SMaxCount< len(values) else SMaxCount#print(self.Students)return SMaxCount,DMaxCountdef __DrawText(self,xy,text,font,color,draw):x = xy[0] #起点坐标xy = xy[1] #起点坐标Yw = xy[2] #宽h = xy[3] #高text_size = draw.textsize(text,font)x1 = x+(w / 2) - (text_size[0] / 2)y1 = y+(h / 2) - (text_size[1] / 2)draw.ink =  color       draw.text((x1,y1), text, fill=None, font = font)def Draw(self):#1、加载值日人员数据SMaxCount,DMaxCount=self.__LoadContents() #2、计算需要的数据weekNo = self.__CalcWeekNum()iweekday = datetime.datetime.weekday(datetime.datetime.now()) weekdayName = self.__WeekDayName()IfSingleWeek = True if weekNo % 2 == 1 else Falsered = 255 + 0 * 256 + 0 * 256 * 256orange = 255 + 165 * 256 + 0 * 256 * 256maroon =128+0*255+ 0* 256 * 256#3、开始画图Width = 770Height = 580bckcolor = (255,255,255)icol = DMaxCount + SMaxCountcols = icol + 2 + 1  #单周行数+又周行数+2标题+1表头colHeight = int( (Height - 4) / cols)rowWidth = int((Width - 4) / 6)#3.1标题img =  Image.new('RGB',size=(Width,Height),color=bckcolor)draw = ImageDraw.Draw(img)# 计算文字居中的位置font = ImageFont.truetype(self.CaptionFont, self.CaptionFontSize)self.__DrawText((2,2,Width,colHeight),self.Caption,font,red,draw)#副标题font = ImageFont.truetype(self.Font, self.FontSize)text = '{0}年{1}月{2}日  {3} 第{4}周'.format(self.CurrentDay.year,self.CurrentDay.month,self.CurrentDay.day, weekdayName,to_chinese(weekNo))self.__DrawText((2,colHeight,rowWidth*2.5,colHeight),text,font,0,draw)#3.2画表格irow = 5+1wtd = rowWidth * irow + 2;for i in range(0,icol+2):if i <2 or i== DMaxCount+1 or i == icol+1:draw.line((2,colHeight*(i+2) ,wtd, colHeight * (i + 2)),self.BroderColor, width=self.BroderLine)else:draw.line((2 + rowWidth,colHeight*(i+2), wtd, colHeight * (i + 2)),self.BroderColor, width=self.BroderLine)hgt = colHeight * (icol + 3);for i in range(0,irow+2):draw.line((2 + rowWidth * i, colHeight * 2, 2 + rowWidth * i, hgt),self.BroderColor,width=self.BroderLine)    draw.line( (2, colHeight * 2, rowWidth, colHeight * 3),self.BroderColor,width=self.BroderLine)#3.3画表头GridX = 2;GridY = colHeight * 2 + 2;self.__DrawText((GridX, GridY + colHeight / 2, rowWidth / 2, colHeight / 2),"周数",font,maroon,draw)    self.__DrawText((GridX + rowWidth / 2, GridY, rowWidth / 2, colHeight / 2),"星期",font,maroon,draw) font = ImageFont.truetype(self.Font, self.FontSize+6)for i in range(0,5):self.__DrawText((GridX + rowWidth * (i+1), GridY + colHeight * 0, rowWidth, colHeight),days[i],font,maroon,draw)  self.__DrawText((GridX, GridY + colHeight * 1, rowWidth, colHeight * DMaxCount),"单周",font,maroon,draw)    self.__DrawText((GridX, GridY + colHeight * (DMaxCount+1), rowWidth, colHeight * SMaxCount),"双周",font,maroon,draw)  #3.4画内容x0 = GridX + rowWidth;y0 = GridY + colHeight;for key,value in self.Students.items():weekflag = key[0]weekday = int(key[1])xoff,yoff = 0,0 fclr = self.FontColorif(weekflag== 'D'): #单周x0+colHeight, y0 + i * colHeight, rowWidth-colHeight, colHeightxoff = rowWidth * (weekday -1)yoff = 0if IfSingleWeek and iweekday+1 == weekday:fclr = redelif(weekflag =='S'):#双周xoff = rowWidth * (weekday -1)yoff = colHeight* DMaxCount if not IfSingleWeek and iweekday+1 == weekday:fclr = redfont = ImageFont.truetype(self.Font, self.FontSize)for i in range(0,len(value)):if fclr== red:txt = '※ '+value[i]else:txt = value[i]self.__DrawText((x0+xoff,y0+yoff+colHeight*i,rowWidth, colHeight),txt,font,fclr,draw) img.save("d:\zr.bmp", 'bmp', quality = 100)        img.show()del drawif __name__ == '__main__':DutyTable().Draw()

用python画值日表相关推荐

  1. 怎么用python画个电脑_python语言还是java如何用python画爱心

    用python绘制爱心的基本步骤如下: 002pc.com对<python语言还是java如何用python画爱心>总结来说,为我们学习Python很实用. 首先先下载安装好python程 ...

  2. 开学季,教你用Python画大学教室座位神分区图!网友直呼“中枪”

    作者 | 丁彦军 转载自恋习Python(ID:sldata2017) 我们上过大学的朋友们都知道,大学没有固定教室也没有固定的座位,所以大家可以随便找个自己喜欢的位置坐下. 别看这些不起眼的座位,感 ...

  3. 圣诞节!教你用Python画棵圣诞树

    作者 | 糖甜甜甜,985高校经管研二,擅长用 Python.R.tableau 等工具结合统计学和机器学习模型做数据分析. 来源 | 经管人学数据分析(ID:DAT-2017) 如何用Python画 ...

  4. 用python画时序图源代码_使用python实现画AR模型时序图

    背景: 用python画AR模型的时序图. 结果: 代码: import numpy as np import matplotlib.pyplot as plt """ ...

  5. 用python画微信捂脸_用 Python 画一个捂脸表情

    微信中的捂脸表情相信大家都不陌生,我见过以及自己使用这个表情的频率都是比较高的,可以说这个表情算是大部分人的主打表情之一了,本文我使用 Python 来画一下这个表情,我们使用到的库还是 turtle ...

  6. echarts词云图形状_怎么用Python画出好看的词云图?

    相信很多人在第一眼看到下面这些图时,都会被其牛逼的视觉效应所吸引,这篇文章就教大家怎么用Python画出这种图. 前期准备 上面的这种图叫做词云图,主要用途是将文本数据中出现频率较高的关键词以可视化的 ...

  7. 用python画动态樱花_利用python画一棵漂亮的樱花树,turtle画图代码大全,此处感谢知乎大佬小白...

    利用python画一棵漂亮的樱花树,turtle画图代码大全,此处感谢知乎大佬小白 此处感谢知乎大佬 小白练手 练习一下比较流行的turtle(海龟库) 画一棵漂亮的樱花树,效果如下: ps: 是动态 ...

  8. python绘制月亮_用python画月亮的代码是什么?

    用python画月亮的代码是什么? 用python画月亮的代码是import turtle as t t.screensize(800,600,"#483d8b")#画布尺寸和颜色 ...

  9. python 画pr曲线

    roc曲线: python 画roc曲线_jacke121的专栏-CSDN博客 import _pickle as cPickle import matplotlib.pyplot as pltxxx ...

最新文章

  1. Android 10.0 系统启动之SystemServer进程-[Android取经之路]
  2. 使用React Router以编程方式导航
  3. [Vue源码分析]自定义事件原理及事件总线的实现
  4. 【洛谷P1795 无穷的序列_NOI导刊2010提高(05)】模拟
  5. 信捷伺服刚性调整_信捷電氣(603416):伺服與PLC增長將加速,口罩機解決方案帶來新增量...
  6. 海底光缆,到底是怎么安装和维护的?
  7. C++调用PyTorch模型:LibTorch
  8. python字典弱引用_如何使用弱引用优化 Python 程序的内存占用?
  9. Flutter RichText 富文本标签样式 局部文字点击事件
  10. java判断读到末尾_Java Web入门之java--第一节 java 简介及开发环境安装
  11. pytest.5.参数化的Fixture
  12. 为什么我会觉得SegmentFault做得越来越力不从心了?
  13. java浏览器安全设置,主编练习win7系统运行java提示“您的安全设置已阻止不可信应用程序运行”的对策...
  14. 了解一些FMS的基本概念
  15. iperf3使用方法说明
  16. 硬时间窗 遗传算法 matlab,基于遗传算法的多种运输工具或带时间窗的路径优化问题(VRP)的求解(MATLAB)...
  17. es 排序 聚合统计_ES聚合排序java
  18. 怎样使用思维导图做计划?分享5个思维导图做计划的模板
  19. mysql锁的级别_mysql 锁和各锁级别
  20. 2022高教社杯 国赛数学建模 A题思路

热门文章

  1. PHP中JSON与数组数据
  2. ABC 246: E - Bishop 2——Flood Fill + 记忆化方向
  3. ffmpeg命令分析-r
  4. 耳机Sense线作用说明
  5. d3-画雷达图-圆形弧线
  6. iTunes的下载windows
  7. 计算机毕业设计(附源码)python学生宿舍管理系统
  8. windows系统学习总结
  9. okhttp原理分析(持续更新),包含okio了解,拦截器以及断点下载的使用
  10. Element 后台管理系统实用表格布局