How to call a background image in Python for drawing?
To draw a picture in Python using a background image, you can utilize the PIL library (Python Imaging Library). Here is an example code:
from PIL import Image, ImageDraw
# 打开背景图片
background_img = Image.open("background.jpg")
# 创建一个新的图像对象,大小与背景图片一致
canvas = Image.new("RGB", background_img.size)
canvas.paste(background_img)
# 创建一个画笔对象
draw = ImageDraw.Draw(canvas)
# 绘制其他内容
draw.rectangle((100, 100, 200, 200), fill="red")
draw.line((300, 300, 400, 400), fill="blue", width=5)
# 保存绘制好的图像
canvas.save("output.jpg")
In the code above, we start by using the Image.open() function to open the background image, then use the Image.new() function to create a new image object with the same size as the background image. Finally, we paste the background image onto the new image object using the paste() function.
Next, we will create a brush object using the ImageDraw.Draw() function, which allows us to draw other contents such as rectangles and lines on the new image object. Finally, we will use the save() function to save the drawn image.
Please make sure you have installed the PIL library in your Python environment. You can use the following command to install it:
pip install Pillow
Replace “background.jpg” in the code with the image path you want to use as the background, and replace “output.jpg” with the file path where you want to save the output.