簡體   English   中英

使用imagemagik / PIL在python中的圖像上添加文本

[英]adding a text over an image in python using imagemagik/PIL

我有一個文字說“我做得很好”。 我想把這段文字放在我產生的可愛背景上。 我想在系統中存在的圖像"image.jpg"上放置"I am doing great" 文本的起點應為X,y(以像素為單位)。

我嘗試了以下代碼段,但出現錯誤:代碼段:

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

font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf",40)
text = "Sample Text"
tcolor = (255,0,0)
text_pos = (100,100)

img = Image.open("certificate.png")
draw = ImageDraw.Draw(img)
draw.text(text_pos, text, fill=tcolor, font=font)
del draw

img.save("a_test.png")

錯誤:

Traceback (most recent call last):
  File "img_man.py", line 13, in <module>
    draw.text(text_pos, text, fill=tcolor, font=font)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 256, in text
    ink, fill = self._getink(fill)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 145, in _getink
    ink = self.palette.getcolor(ink)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImagePalette.py", line 62, in getcolor
    self.palette = map(int, self.palette)
ValueError: invalid literal for int() with base 10: '\xed'

似乎是PIL中的錯誤: http : //grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report

我可以嘗試任何解決方法嗎?

我遇到了同樣的錯誤,似乎是PNG調色板處理中Pil / Pillow中的錯誤。 解決方法是在繪制文本之前將圖像轉換為RBG:

img = img.convert('RGB')

查看ImageDraw模塊text方法(Google在“ pil text”中排名最高)。您還需要ImageFont模塊,該模塊具有相關的示例代碼:

import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 10), "hello", font=font)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM