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

标签 python python-imaging-library

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

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/

相关文章:

python - 我如何确保 flask 应用程序已在所有路线上获得授权?

python - 即使函数设置参数不移动,PygameSprites也会移出屏幕

python - 如何在 python 中将图像从 StringIO 读取到 PIL

python - 如何使用 PIL 使所有白色像素透明?

python-imaging-library - 如何绘制透明多边形?

python - 如何强制 Pillow 将图像调整为任意大小?

python - PIL透视变换,计算出(a,b,c,d,e,f,g,h)

Python:语句中使用的循环变量未更新

Python 列表到 XML,反之亦然

python - 获取 pandas 列表列中元素频率的有效方法