【问题标题】:Make to make text size auto adjust to an image with PIL使用 PIL 使文本大小自动调整为图像
【发布时间】:2019-05-30 14:11:47
【问题描述】:

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

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 之间。无论哪个先实现。

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

【问题讨论】:

  • 这不是question 你从一开始就想要的!

标签: python python-imaging-library


【解决方案1】:

你可以使用函数ImageFont.truetype()的第二个参数来增加字体大小。

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

【讨论】:

  • 字体大小必须动态变化,给你一个静态数字。
  • OP 要求提供动态字体大小
【解决方案2】:

所以运气好的话,这里是下面的代码。请注意,一些变量从上面的原始代码中更改了名称,但这有效。

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

【讨论】:

  • 感谢您粘贴此内容。我遇到了同样的问题,找不到任何东西。我想知道是否有更好的解决方案。
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多