PIL 如何根据图像大小缩放文本大小 [英] PIL how to scale text size in relation to the size of the image

查看:32
本文介绍了PIL 如何根据图像大小缩放文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态缩放文本以放置在不同但已知尺寸的图像上.文本将作为水印应用.有什么方法可以根据图像尺寸缩放文本吗?我不要求文本占据整个表面区域,只是为了足够可见,以便易于识别且难以删除.我正在使用 Python 图像库版本 1.1.7.在 Linux 上.

I'm trying to dynamically scale text to be placed on images of varying but known dimensions. The text will be applied as a watermark. Is there any way to scale the text in relation to the image dimensions? I don't require that the text take up the whole surface area, just to be visible enough so its easily identifiable and difficult to remove. I'm using Python Imaging Library version 1.1.7. on Linux.

我希望能够设置文本大小与图像尺寸的比例,比如大小的 1/10 之类的.

I would like to be able to set the ratio of the text size to the image dimensions, say like 1/10 the size or something.

我一直在查看字体大小属性来更改大小,但我没有成功创建算法来缩放它.我想知道是否有更好的方法.

I have been looking at the font size attribute to change the size but I have had no luck in creating an algorithm to scale it. I'm wondering if there is a better way.

关于如何实现这一目标的任何想法?

Any ideas on how I could achieve this?

谢谢

推荐答案

您可以增加字体大小,直到找到合适的字体大小.font.getsize() 是告诉你渲染文本有多大的函数.

You could just increment the font size until you find a fit. font.getsize() is the function that tells you how large the rendered text is.

from PIL import ImageFont, ImageDraw, Image

image = Image.open('hsvwheel.png')
draw = ImageDraw.Draw(image)
txt = "Hello World"
fontsize = 1  # starting font size

# portion of image width you want text width to be
img_fraction = 0.50

font = ImageFont.truetype("arial.ttf", fontsize)
while font.getsize(txt)[0] < img_fraction*image.size[0]:
    # iterate until the text size is just larger than the criteria
    fontsize += 1
    font = ImageFont.truetype("arial.ttf", fontsize)

# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("arial.ttf", fontsize)

print('final font size',fontsize)
draw.text((10, 25), txt, font=font) # put the text on the image
image.save('hsvwheel_txt.png') # save it

如果这对你来说不够有效,你可以实现一个寻根方案,但我猜测 font.getsize() 函数与你的其余部分相比是小土豆图像编辑过程.

If this is not efficient enough for you, you can implement a root-finding scheme, but I'm guessing that the font.getsize() function is small potatoes compared to the rest of your image editing processes.

这篇关于PIL 如何根据图像大小缩放文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆