gpt4 book ai didi

python - 使用 PIL 使文本大小自动调整为图像

转载 作者:太空狗 更新时间:2023-10-29 21:02:06 25 4
gpt4 key购买 nike

我试图让一些文本重叠在图像上,我有以下代码。

from PIL import Image, ImageDraw, ImageFont

msg = "This is a test phrase, so please shrink the text."

im = Image.open("test.jpg")
draw = ImageDraw.Draw(im)

W, H = im.size

myFont =
ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf")

w, h = draw.textsize(msg, font=myFont)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black", font=myFont)

im.save("sample-out.png", "PNG")

我需要的是在中间缩放的文本,但像素宽度和高度之间为 1600,300。以先达到的为准。

我想这与字体大小的增加有关,但我无法弄清楚。

最佳答案

幸运的是,下面是代码。请注意,一些变量更改了上面原始代码的名称,但这有效。

from PIL import ImageFont, ImageDraw, Image

image = Image.open('test.jpg')
draw = ImageDraw.Draw(image)
txt = "share/fonts/truetype/customfonts/KeepC"
fontsize = 1 # starting font size

W, H = image.size

# portion of image width you want text width to be
blank = Image.new('RGB',(1000, 300))


font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)
print image.size
print blank.size

while (font.getsize(txt)[0] < blank.size[0]) and (font.getsize(txt)[1] < blank.size[1]):
# iterate until the text size is just larger than the criteria
fontsize += 1
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)

# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)

w, h = draw.textsize(txt, font=font)

print 'final font size',fontsize
draw.text(((W-w)/2,(H-h)/2), txt, font=font, fill="black") # put the text on the image
image.save('sample-out.png') # save it

关于python - 使用 PIL 使文本大小自动调整为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54031588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com