简体   繁体   English

如何使用 Python ImageDraw 库更改字体大小

[英]How to change font size using the Python ImageDraw Library

I am trying to change the font size using python's ImageDraw library.我正在尝试使用 python 的 ImageDraw 库更改字体大小。

You can do something like this :你可以这样

fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16  =  ImageFont.truetype ( fontPath, 16 )

im  =  Image.new ( "RGB", (200,50), "#ddd" )
draw  =  ImageDraw.Draw ( im )
draw.text ( (10,10), "Run awayyyy!", font=sans16, fill="red" )

The problem is that I don't want to specify a font.问题是我不想指定字体。 I want to use the default font and just change the size of the font.我想使用默认字体,只需更改字体的大小。 This seems to me that it should be simple, but I can't find documentation on how to do this.在我看来,这应该很简单,但我找不到有关如何执行此操作的文档。

Per PIL's docs , ImageDraw 's default font is a bitmap font, and therefore it cannot be scaled.根据PIL 的文档ImageDraw的默认字体是位图字体,因此无法缩放。 For scaling, you need to select a true-type font.对于缩放,您需要选择一种真字体。 I hope it's not difficult to find a nice truetype font that "looks kinda like" the default font in your desired font-size!我希望不难找到一个“看起来有点像”你想要的字体大小的默认字体的不错的 truetype 字体!

Just do this就这样做

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

def image_char(char,image_size, font_size):
        img = Image.new("RGB", (image_size, image_size), (255,255,255))
        print img.getpixel((0,0))
        draw = ImageDraw.Draw(img)
        font_path = "/Users/admin/Library/Fonts/InputSans-Regular.ttf"
        font = ImageFont.truetype(font_path, font_size)

        draw.text((5, 5), char, (0,0,0),font=font)
        img.show()

main():
       image_char("A",36,16)

if __name__ == '__main__':
       sys.exit(main())

You could scale the image down, draw the text and then scale the image up again:您可以缩小图像,绘制文本,然后再次放大图像:

im = ImageOps.scale(im, 0.5)
draw = ImageDraw.Draw(im)
draw.text((0, 0),"MyText",(0,0,0))
im = ImageOps.scale(im, 2)

This effectively increases the font size by a factor of 2.这有效地将字体大小增加了 2 倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM