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

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

问题描述

我试图动态缩放文字以放置在不同但已知尺寸的图像上。该文本将作为水印应用。有没有什么办法来缩放与图像尺寸有关的文字?我不要求文本占据整个表面区域,只是为了使其易于识别,难以清除。我正在使用Python影像库版本1.1.7。在Linux上。



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

我一直在寻找字体大小属性来改变大小,但我没有创建一个算法来扩展它的运气。我想知道是否有更好的方法。



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

谢谢

解决方案

你可以增加字体大小,直到找到合适的。 font.getsize()是告诉你这个呈现的文本有多大的函数。

  import ImageFont,ImageDraw,Image 
$ b $ image = Image.open('hsvwheel.png')
draw = ImageDraw.Draw(image)
txt =你好世界
fontsize = 1#开始字体大小

#你想要的图像宽度部分文本宽度是
img_fraction = 0.50

font = ImageFont.truetype(arial.ttf,fontsize)
而font.getsize(txt)[0]< img_fraction * image.size [0]:
#迭代,直到文本大小只是大于条件
fontsize + = 1
font = ImageFont.truetype(arial.ttf,fontsize )

#可选择去增加以确保它小于条件
fontsize - = 1
font = ImageFont.truetype(arial.ttf,fontsize)

print'final font size',fontsize
draw.text((10,25),txt,font = font)#将文字放在图片
image.save(' hsvwheel_txt.png')#保存

如果这个效率不够高,但是我猜测 font.getsize()函数与其他图像编辑过程相比是小土豆。

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.

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?

Thanks

解决方案

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.

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

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天全站免登陆