您可以不使用composite()
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
source_img = Image.open(file_name).convert("RGBA")
draw = ImageDraw.Draw(source_img)
draw.rectangle(((0, 00), (100, 100)), fill="black")
draw.text((20, 70), "something123", font=ImageFont.truetype("font_path123"))
source_img.save(out_file, "JPEG")
您可以创建具有按钮大小的空图像,并在其上放置文本,然后将该图像放置在source_img
。这样,长文本将被剪切为按钮的大小。
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
source_img = Image.open("source.jpg").convert("RGBA")
# create image with size (100,100) and black background
button_img = Image.new('RGBA', (100,100), "black")
# put text on image
button_draw = ImageDraw.Draw(button_img)
button_draw.text((20, 70), "very loooooooooooooooooong text", font=ImageFont.truetype("arial"))
# put button on source image in position (0, 0)
source_img.paste(button_img, (0, 0))
# save in new file
source_img.save("output.jpg", "JPEG")
编辑:我使用ImageFont.getsize(text)
来获取文本大小并创建具有正确大小的按钮。
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
source_img = Image.open("input.jpg").convert("RGBA")
font = ImageFont.truetype("arial")
text = "very loooooooooooooooooong text"
# get text size
text_size = font.getsize(text)
# set button size + 10px margins
button_size = (text_size[0]+20, text_size[1]+20)
# create image with correct size and black background
button_img = Image.new('RGBA', button_size, "black")
# put text on button with 10px margins
button_draw = ImageDraw.Draw(button_img)
button_draw.text((10, 10), text, font=font)
# put button on source image in position (0, 0)
source_img.paste(button_img, (0, 0))
# save in new file
source_img.save("output.jpg", "JPEG")
0
我想在其中绘制一个矩形和一个文本,这是我的代码的一部分,有点混淆:
这会同时绘制它们,但它们是分开的:文本在矩形下方。而我希望在矩形内绘制文本。我怎样才能做到这一点?如果我一定撰写他们还是什么?