from PIL import Image,ImageDraw,ImageFont
import random
import string
设置图片的大小,文字的字体、大小、颜色设置为随机选取,这样看起来更加美观。
size=(200,100)
fontSize=30
font = ImageFont.truetype('VeraMoBI.ttf',fontSize)
image1 = Image.new('RGBA',size,(255,)*4)
texts = ''.join(random.sample(string.ascii_letters + string.digits, 5))
--------------------------------------------------------------------------- OSError Traceback (most recent call last) Cell In[3], line 3 1 size=(200,100) 2 fontSize=30 ----> 3 font = ImageFont.truetype('VeraMoBI.ttf',fontSize) 4 image1 = Image.new('RGBA',size,(255,)*4) 5 texts = ''.join(random.sample(string.ascii_letters + string.digits, 5)) File /opt/conda/lib/python3.12/site-packages/PIL/ImageFont.py:879, in truetype(font, size, index, encoding, layout_engine) 876 return FreeTypeFont(font, size, index, encoding, layout_engine) 878 try: --> 879 return freetype(font) 880 except OSError: 881 if not is_path(font): File /opt/conda/lib/python3.12/site-packages/PIL/ImageFont.py:876, in truetype.<locals>.freetype(font) 875 def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont: --> 876 return FreeTypeFont(font, size, index, encoding, layout_engine) File /opt/conda/lib/python3.12/site-packages/PIL/ImageFont.py:284, in FreeTypeFont.__init__(self, font, size, index, encoding, layout_engine) 282 load_from_bytes(f) 283 return --> 284 self.font = core.getfont( 285 font, size, index, encoding, layout_engine=layout_engine 286 ) 287 else: 288 load_from_bytes(cast(IO[bytes], font)) OSError: cannot open resource
开始向图片内添加字符串,并将字体进行旋转,遍历结束后保存。
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')