# 确保字体文件路径正确
font_path = 'C:/Windows/Fonts/方正粗黑宋简体.ttf'
if not os.path.exists(font_path):
print(f"字体文件不存在:{font_path}")
exit()
# 加载字体
font = ImageFont.truetype(font_path, 50)
myfont = ImageFont.truetype(font_path, 30)
# 打开图像
image = Image.open('1.png')
draw = ImageDraw.Draw(image)
# 定义文本内容
text = "Hello, World!"
text2 = "Hello, World!"
# 计算文本大小和旋转后的文本图像尺寸
text_bbox = draw.textbbox((0, 0), text, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
text_bbox2 = draw.textbbox((0, 0), text2, font=myfont)
text_width2 = text_bbox2[2] - text_bbox2[0]
text_height2 = text_bbox2[3] - text_bbox2[1]
# 定义旋转角度
angle = -7.3
angle2 = -6.9
# 创建一个透明图像,大小足够容纳旋转后的文本
rotated_text_image = Image.new('RGBA', (text_width, text_height))
rotated_text_draw = ImageDraw.Draw(rotated_text_image)
rotated_text_draw.text((text_width/2, text_height/2), text, font=font, fill='black', anchor='mm')
rotated_text_image = rotated_text_image.rotate(angle, expand=True)
rotated_text_image2 = Image.new('RGBA', (text_width2, text_height2))
rotated_text_draw2 = ImageDraw.Draw(rotated_text_image2)
rotated_text_draw2.text((text_width2/2, text_height2/2), text2, font=myfont, fill='black', anchor='mm')
rotated_text_image2 = rotated_text_image2.rotate(angle2, expand=True)
# 计算粘贴位置的坐标
paste_x = 215
paste_y = 425
paste_x2 = 281
paste_y2 = 558
# 将旋转后的文本粘贴到主图像上
image.paste(rotated_text_image, (paste_x, paste_y), rotated_text_image)
image.paste(rotated_text_image2, (paste_x2, paste_y2), rotated_text_image2)
# 显示或保存图像
image.show()
PILLOW生成图文,图像和文字的处理(python)
最新推荐文章于 2024-06-11 19:05:07 发布