【问题标题】:Editing font attributes when transferring string to image将字符串传输到图像时编辑字体属性
【发布时间】:2020-06-08 17:53:11
【问题描述】:

我一直在 Jupyter Notebook 中使用 Python 3 和 Pillow 来获取用户输入的字符串并将其转换为图像。

一旦字符串成功更改为图像,图像的字体大小和样式仍然很小,当我尝试编辑与文本宽度和高度相关的变量时不会改变,但边框空间确实会改变.

例如,如果我放大文本的宽度或高度,字体不会改变,但字体周围的白边会改变。如果有人知道如何解决这个问题,请告诉我。

from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("Verdana.ttf", 100) #seems to have no impact on the program

userinput0000 = input("Enter String Here:")
bgcolor = 'white'
txtcolor = 'black'
text_width, text_height = (5 , 5) # (w,h) changes the size of the white box surrounding the string

userinput0000img = Image.new("RGB",(text_width, text_height), bgcolor)
draw = ImageDraw.Draw(userinput0000img)
draw.text((5, 5), userinput0000, txtcolor) #(x,y)changes the xy coordinates of the string

userinput0000img.show()

im = Image.open("Desktop/0001.jpg")
x, y = userinput0000img.size
im.paste(userinput0000img,(0,0,x,y))
im.show()

当前代码输出:

这是我发现有用的两篇 Stack Overflow 帖子,但似乎都没有解决同一类型的问题。

我还阅读了枕头手册(链接如下),没有发现类似情况的参考。

https://pillow.readthedocs.io/en/latest/handbook/tutorial.html

【问题讨论】:

    标签: python python-3.x image jupyter-notebook python-imaging-library


    【解决方案1】:

    您错过了在您的ImageDraw.text 调用中添加font 参数,从而引用了您创建的字体实例。

    所以,改变

    draw.text((5, 5), userinput0000, txtcolor) 
    

    类似

    draw.text((5, 5), userinput0000, txtcolor, font=font) 
    

    你就完成了。

    希望有帮助!

    【讨论】:

    • 非常感谢,这解决了问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2017-04-17
    • 2013-05-16
    • 1970-01-01
    相关资源
    最近更新 更多