如果您不太关心速度,可以使用组合来实现:
- 在空白的
RGBA
图像上绘制带光晕颜色的文本
- 对其进行模糊处理
- 再次绘制文本颜色的文本
- 反转此图像以获取组合遮罩
- 与原始图像“合并”
例如:
import sys
import Image, ImageChops, ImageDraw, ImageFont, ImageFilter
def draw_text_with_halo(img, position, text, font, col, halo_col):
halo = Image.new('RGBA', img.size, (0, 0, 0, 0))
ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col)
blurred_halo = halo.filter(ImageFilter.BLUR)
ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col)
return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))
if __name__ == '__main__':
i = Image.open(sys.argv[1])
font = ImageFont.load_default()
txt = 'Example 1234'
text_col = (0, 255, 0)
halo_col = (0, 0, 0)
i2 = draw_text_with_halo(i, (20, 20), txt, font, text_col, halo_col)
i2.save('halo.png')
它有许多优点:
- 结果平滑且美观
- 您可以选择不同的过滤器而不是
BLUR
以获得不同的“光晕”效果
- 即使使用非常大的字体,它仍然看起来很棒
要获得更厚的光晕,您可以使用以下类似的过滤器:
kernel = [
0, 1, 2, 1, 0,
1, 2, 4, 2, 1,
2, 4, 8, 4, 1,
1, 2, 4, 2, 1,
0, 1, 2, 1, 0]
kernelsum = sum(kernel)
myfilter = ImageFilter.Kernel((5, 5), kernel, scale = 0.1 * sum(kernel))
blurred_halo = halo.filter(myfilter)
scale = 0.1 * sum(kernel)
这部分代码可以让光晕更厚(小值)或者更暗淡(大值)。