はPIL

1

編集を使ってPython 2.7で画像にテキストを書き込みます。はPIL

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

コードを入力すると「Hello world」が黒で表示されます。

私はjpgイメージに "Hello World"を書き込もうとしているpythonスクリプトを持っていますが、ファイルを保存するとテキストは書き込まれません。 私は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') 

を私はまた、画像は色がグレースケールになって保存されている場合、その理由があるかもしれないことに気付きました?

答えて

3

次のコードは私のために働いたが、私は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() 

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私がフォントを持っていないが、またのpython 2.7、ちょうどあなたのコードのようなJPGイメージで動作するように表示されます(しかし、私は、フォントを持っていません)

あなたのコード(私の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

+0

こんにちは、私は私のミスをしたところ、実現 draw.text((30,10)、 "Hello World" の、(0、0、0、255)、フォント=フォントを持っていました)、黒ではなく白で書く。 ご協力いただきありがとうございます。 – RedQuirk