【发布时间】:2020-10-25 10:58:56
【问题描述】:
我一直在使用 PIL 图片
我正在尝试在图像上绘制文本。我希望这个文本像大多数模因一样具有黑色轮廓。我试图通过在前面的字母后面画一个更大字体的阴影字母来做到这一点。我已经相应地调整了阴影的 x 和 y 位置。不过阴影稍微偏了一点。前面的字母应该正好在阴影字母的中间,但事实并非如此。问号肯定不是水平居中的,所有的字母在垂直方向上都太低了。轮廓也不好看。
下面是生成上图的最小可重现示例。
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 次,但这些也不是最佳的,如下所示
生成上图的代码
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')
【问题讨论】:
-
看起来像这样的副本:stackoverflow.com/questions/41556771/…
-
@jdaz 那里的答案使用我列出的第二种方法,这不是最佳解决方案
标签: python image image-processing python-imaging-library