使用PIL在python 2.7中将文本写入图像

时间:2017-03-19 11:31:05

标签: python image-processing text python-imaging-library image-manipulation

编辑: 但是我的代码有效

draw.text((30,10), "Hello World", (255, 255, 255, 255),font=font)

写道" Hello World"像白色。如果将其更改为

draw.text((30,10), "Hello World", (255, 255, 255, 255),font=font)

输入代码" Hello world"将用黑色写成。

我有一个python脚本试图写" Hello World"到jpg图像但是当我保存文件时没有写入文字,任何想法? 我使用的是python 2.7和Pillow。

我还查看了此文档:http://pillow.readthedocs.io/en/3.1.x/reference/ImageDraw.html

代码:

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

pattern = Image.open("DANK.jpg", "r").convert('RGBA') 

size = width, height = pattern.size
draw = ImageDraw.Draw(pattern,'RGBA')
font = ImageFont.truetype("Font.ttf", 3)

draw.text((30,10), "Hello World", (255, 255, 255, 255),font=font)
pattern.save('sample-out.jpg')

我还注意到,当图像保存时,颜色会变成灰度,为什么会这样?

1 个答案:

答案 0 :(得分:4)

以下代码对我有用,但我使用了python 3和png。我将图像放在与代码相同的目录中,然后在图像上写入文本。

from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('lena.png').convert('RGBA')

# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))

# get a font
fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)

# draw text, half opacity
d.text((100,100), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.text((100,160), "World", font=fnt, fill=(255,255,255,255))

out = Image.alpha_composite(base, txt)

out.show()

我没有字体,但它似乎也可以使用python 2.7和jpg图像就像你的代码一样(但我没有字体)

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

pattern = Image.open("DANK.jpg", "r").convert('RGBA')

size = width, height = pattern.size
draw = ImageDraw.Draw(pattern,'RGBA')
#font = ImageFont.truetype("Font.ttf", 3)

draw.text((30,10), "Hello World", (0, 0, 0, 0))#,font=font)
pattern.save('sample-out.jpg')

enter image description here

与你的代码最相似(使用我的Ubuntu 16.04),下面也会在图像上呈现文字。

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

pattern = Image.open("DANK.jpg", "r").convert('RGBA')

size = width, height = pattern.size
draw = ImageDraw.Draw(pattern,'RGBA')
font = ImageFont.truetype("Pillow/Tests/fonts/FreeMono.ttf", 100)

draw.text((300,10), "Hello World", (0, 0, 0, 0),font=font)
pattern.save('sample-out.jpg')

enter image description here