1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import sys import os from PIL import Image, ImageDraw, ImageFont CHILD_W = CHILD_H = 16
runDir = os.path.split( os.path.realpath( sys.argv[0] ) )[0] txt = open(runDir + "\\text.txt", encoding="utf-8").read()
font = ImageFont.truetype(runDir + '\\Font.ttf', CHILD_W)
print("文本:",txt) print("字体:",runDir + '\\Font.ttf') print("原图片:",runDir + "\\import.JPG") print("——"*10)
if __name__ == '__main__': imgSrc = Image.open(runDir + "\\import.JPG") w, h = imgSrc.size
imgChild = Image.new("RGB", (CHILD_W, CHILD_H)) imgDst = Image.new("RGB", (CHILD_W*w, CHILD_H*h) )
textW, textH = font.getsize("迷") offsetX = (CHILD_W - textW) >> 1 offsetY = (CHILD_H - textH) >> 1
charIndex = 0 draw = ImageDraw.Draw(imgChild) print("开始处理图片...") for y in range(h): print("进度:" + str (int(y/h*100))+"%" ) for x in range(w): draw.rectangle( (0, 0, CHILD_W, CHILD_H), fill = 'lightgray' )
draw.text( (offsetX, offsetY), txt[charIndex], font = font, fill = imgSrc.getpixel((x, y)) )
imgDst.paste(imgChild, (x*CHILD_W, y*CHILD_H))
charIndex += 1 if charIndex == len(txt): charIndex = 0
print("进度:100%") print("正在保存文件...") imgDst.save(runDir + "\\Output.JPG") print(runDir + "\\Output.JPG") print("完成!")
|