所需模块:pillow
安装方法:Win + R 打开运行界面,输入cmd点击肯定进入终端界面,使用以下命令安装pillow模块。python
pip install pillow
NB(注意): 这里pillow模块安装时要使用pillow,导入是则使用PIL。
模块导入方法以下:web
from PIL import Image from PIL import ImageDraw from PIL import ImageFont
Image:提供了加载图像和建立新图像的功能
ImageDraw: 提供了建立新图像、对现有图像进行注释或润色的功能
ImageFont: 提供了字体选择功能app
使用设计者模式书写代码,代码以下:less
class newYear: def __init__(self): self.word_size = 25 self.word1 = "新" self.word2 = "年" self.word3 = "快" self.word4 = "乐" self.image1 = None self.image2 = None self.image3 = None self.image4 = None self.component1 = None self.component2 = None def imageDraw(self, word): image1 = Image.new("RGB", (self.word_size, self.word_size), "white").convert("L") work_bench = ImageDraw.Draw(im=image1) work_bench.text(xy=(0, 0), text=u'{}'.format(word), fill="#000000", font=ImageFont.truetype('C:/Windows/Fonts/simsun.ttc', self.word_size)) # image1.save("C:/Users/15025/Desktop/{}.jpg".format(word), "JPEG") return image1 def createComponent(self, image1, image2): bench_size = (pow(self.word_size, 2), pow(self.word_size, 2)) new_bench = Image.new('L', bench_size, "white") for w in range(image1.width): for h in range(image1.height): if image1.getpixel((w, h)) < 127: new_bench.paste(image2, (w * image2.width, h * image2.height)) return new_bench def mergeComponent(self): bench_size = (1300, 800) new_bench = Image.new('L', bench_size, "white") new_bench.paste(self.component1, (0, 0)) new_bench.paste(self.component2, (700, 0)) new_bench.save("C:/Users/15025/Desktop/blessing.jpg") def createBlessing(self): self.image1 = self.imageDraw(self.word1) self.image2 = self.imageDraw(self.word2) self.image3 = self.imageDraw(self.word3) self.image4 = self.imageDraw(self.word4) self.component1 = self.createComponent(self.image1, self.image3) self.component2 = self.createComponent(self.image2, self.image4) self.mergeComponent() class wordBlessing: unit_dict = { "newyear": newYear } @classmethod def create_unit(cls, unit_type): return cls.unit_dict.get(unit_type)() class App: blessing = wordBlessing def blessingMake(self, blessing_type): unit = self.blessing.create_unit(blessing_type) unit.createBlessing() if __name__ == "__main__": app = App() app.blessingMake("newyear")
首先由于须要中文输出,字体选择上不可以随意选择,只可以选择适合中文输出的字体,如这里使用的是simsun.ttc
字体格式,一般字体库位于咱们电脑的C:/Windows/Fonts/
中的Fonts
文件夹下,字体一般有两种后缀名,ttc
和ttf
。查看电脑内全部可用字体代码以下:svg
import matplotlib.font_manager print(matplotlib.font_manager.findSystemFonts(fontpaths=None))
能够自行尝试其余格式的字体,这里不作过多尝试。
该程序整体思路是建立所须要的汉字的单个图片,尺寸均为25 * 25
,将新
字存放在变量self.word1
中,将年
字存放在变量self.word2
中,将快
字存放在变量self.word3
中,将乐
字存放在变量self.word4
中,由imageDraw()
函数完成。以后由于要进行文字嵌套,咱们知道新
字应该嵌套快
字,年
字应该嵌套乐
字,因此咱们须要将新
与快
字组合起来并存储到变量self.component1
中,同理将年
与乐
字组合存储到self.component2
,这一部分由函数createComponent()
完成。最终咱们须要将两个component
组合起来放置在一个画布图像的固定位置,造成最后的图像,由mergeComponent()
函数完成。函数