gpt4 book ai didi

python - 在Python中的图像上大纲文本

转载 作者:行者123 更新时间:2023-12-03 13:52:46 26 4
gpt4 key购买 nike

我一直在使用PIL图片
我正在尝试在图像上绘制文本。我希望此文字像大多数模因一样具有黑色轮廓。我试图通过在前面的字母后面绘制较大字体的阴影字母来实现此目的。我已经相应地调整了阴影的x和y位置。阴影虽然略微掉了。前面的字母应恰好在阴影字母的中间,但事实并非如此。问号当然不是水平居中,所有字母垂直都太低。轮廓也不好看。
enter image description here

下面是产生上面图像的最小可复制示例。
Link to the font
Link to original image

from PIL import Image, ImageDraw, ImageFont

caption = "Why is the text slightly off?"
img = Image.open('./example-img.jpg')
d = ImageDraw.Draw(img)
x, y = 10, 400
font = ImageFont.truetype(font='./impact.ttf', size=50)
shadowFont = ImageFont.truetype(font='./impact.ttf', size=60)
for idx in range(0, len(caption)):
char = caption[idx]
w, h = font.getsize(char)
sw, sh = shadowFont.getsize(char) # shadow width, shadow height
sx = x - ((sw - w) / 2) # Shadow x
sy = y - ((sh - h) / 2) # Shadow y
# print(x,y,sx,sy,w,h,sw,sh)
d.text((sx, sy), char, fill="black", font=shadowFont) # Drawing the text
d.text((x, y), char, fill=(255,255,255), font=font) # Drawing the text
x += w + 5

img.save('example-output.jpg')


Another approach包括在主文本后面的黑色位置上绘制4次黑色的文本,这些位置的位置略高,略低,略向左和略向右,但是这些也不是最佳选择,如下所示
enter image description here
代码产生上面的图像

    from PIL import Image, ImageDraw, ImageFont

caption = "Why does the Y and i look weird?"
x, y = 10, 400
font = ImageFont.truetype(font='./impact.ttf', size=60)
img = Image.open('./example-img.jpg')
d = ImageDraw.Draw(img)
shadowColor = (0, 0, 0)
thickness = 4
d.text((x - thickness, y - thickness), caption, font=font, fill=shadowColor, thick=thickness)
d.text((x + thickness, y - thickness), caption, font=font, fill=shadowColor, thick=thickness)
d.text((x - thickness, y + thickness), caption, font=font, fill=shadowColor, thick=thickness)
d.text((x + thickness, y + thickness), caption, font=font, fill=shadowColor, thick=thickness)
d.text((x, y), caption, spacing=4, fill=(255, 255, 255), font=font) # Drawing the text
img.save('example-output.jpg')

最佳答案

我不知道从哪个版本开始,但是关于a year ago Pillow添加了文本描边。如果您最近没有更新,则可能需要更新它。 stroke_width为2的用法示例:

from PIL import Image, ImageDraw, ImageFont

caption = 'I need to update my Pillow'
img = Image.open('./example-img.jpg')
d = ImageDraw.Draw(img)
font = ImageFont.truetype('impact.ttf', size=50)
d.text((10, 400), caption, fill='white', font=font,
stroke_width=2, stroke_fill='black')
img.save('example-output.jpg')

关于python - 在Python中的图像上大纲文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62737084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com