from PIL import Image,ImageDraw,ImageFont
import random
import string
设置图片的大小,文字的字体、大小、颜色设置为随机选取,这样看起来更加美观。
size=(200,100)
fontSize=30
font = ImageFont.truetype('/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf',fontSize)
image1 = Image.new('RGBA',size,(255,)*4)
texts = ''.join(random.sample(string.ascii_letters + string.digits, 5))
开始向图片内添加字符串,并将字体进行旋转,遍历结束后保存。
x = 10
xplus = 15
for text in texts:
fontColor = (random.randint(0,250),random.randint(0,250),random.randint(0,250))
draw = ImageDraw.Draw(image1)
draw.text((x,4),text,fill=fontColor,font=font)
rot = image1.rotate(random.randint(-10,10),expand=0)
fff = Image.new('RGBA',rot.size,(255,)*4)
image1 = Image.composite(rot,fff,rot)
x += xplus
image1.save('xx_demo_p.png')