Sam*_*Sam 6 python image image-processing python-imaging-library
我一直在使用 PIL Image
我正在尝试在图像上绘制文本。我希望这个文本像大多数模因一样有一个黑色的轮廓。我试图通过在前面的字母后面画一个更大字体的阴影字母来做到这一点。我相应地调整了阴影的 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')Run Code Online (Sandbox Code Playgroud)
另一种方法包括在正文后面的略高、略低、略左侧和略右侧的位置以黑色绘制文本 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')Run Code Online (Sandbox Code Playgroud)
我不知道从哪个版本开始,但大约一年前Pillow 添加了文本抚摸。如果您最近没有这样做,您可能需要更新它。使用stroke_width2 的示例用法:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1028 次 |
| 最近记录: |