如何在图片上添加文字?Python中如何在空白画布上添加字符串?
Hey Lee, let's tackle your two questions step by step—here's what you need to know:
You've got a couple of solid options here, depending on whether you prefer a visual tool or code-based approach:
可视化工具(比如Photoshop/GIMP)
Super straightforward:- Open your target image in the tool
- Select the text tool (usually marked with a "T" icon)
- Click in the blank space above your image, type your text
- Adjust font, size, color, and alignment to your liking, then save the edited image
Python代码实现(基于Pillow库)
Great if you need to batch process images or automate the task:from PIL import Image, ImageDraw, ImageFont # 加载目标图片 img = Image.open("your_image.jpg") width, height = img.size # 创建新画布,在顶部预留100像素的文字区域 new_canvas = Image.new("RGB", (width, height + 100), "white") new_canvas.paste(img, (0, 100)) # 将原图粘贴到文字区域下方 # 初始化绘图对象 draw = ImageDraw.Draw(new_canvas) # 设置字体(可替换为本地字体路径) font = ImageFont.truetype("arial.ttf", 40) text_content = "你的自定义文字" # 让文字水平居中显示 text_width = draw.textlength(text_content, font=font) draw.text(((width - text_width) / 2, 30), text_content, font=font, fill="black") # 保存最终图片 new_canvas.save("image_with_top_text.jpg")
This depends on what kind of Canvas you're working with—here are the two most common scenarios:
Tkinter GUI画布
If you're building a desktop app with Tkinter, use thecreate_text()method directly on the Canvas widget:import tkinter as tk root = tk.Tk() # 创建一块400x300的空白白色画布 canvas = tk.Canvas(root, width=400, height=300, bg="white") canvas.pack() # 在画布上方添加文字 # 参数依次为:文字中心x坐标、y坐标、内容、字体、颜色 canvas.create_text(200, 50, text="Tkinter画布上的文字", font=("Arial", 20), fill="navy") root.mainloop()调整
x和y值可以精准控制文字位置,y值越小,文字越靠上。PIL空白画布(用于生成图片)
If you're creating a standalone image with a blank canvas, use Pillow's ImageDraw module:from PIL import Image, ImageDraw, ImageFont # 创建一块400x300的空白白色画布 blank_canvas = Image.new("RGB", (400, 300), "white") draw = ImageDraw.Draw(blank_canvas) # 设置字体和文字内容 font = ImageFont.truetype("arial.ttf", 32) draw.text((30, 25), "空白画布上的文字", font=font, fill="darkgreen") # 保存或展示结果 blank_canvas.save("blank_canvas_text.png") blank_canvas.show()
内容的提问来源于stack exchange,提问作者Lee

