簡體   English   中英

使用PIL在圖像上添加文本。 錯誤信息

[英]Add text on image using PIL. error message

我有以下代碼,可以下載圖像並在圖像上寫入文本。 下載工作正常。 錯誤發生在draw.text行上。 我不確定為什么會出錯。 ttf文件位於正確的位置,並且路徑名正確。 我使用pip安裝了Pillow。 我沒有遇到任何錯誤。

import urllib

urlSA = "http://www.wpc.ncep.noaa.gov/archives/sfc/" + year + "/usfntsfc" + year + month + day + "09.gif"
savedFileSA = "C:/images/sa2000/" + month + day + yearShort + ".jpg"

urllib.urlretrieve (urlSA, savedFileSA)

# Add a title to the SA image
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

img = Image.open(savedFileSA)
draw = ImageDraw.Draw(img)
fnt = ImageFont.truetype("C:/images/arial.ttf", 12)
draw.text((10, 10),"Sample Text",(3,3,3),font=fnt)

img.save(savedFileSA)

錯誤:

Traceback (most recent call last):
  File "C:\images\storm_reports_Arc103.py", line 105, in <module>
draw.text((10, 10),"Sample Text",(3,3,3),font=fnt)
  File "C:\Python27\ArcGIS10.3\lib\site-packages\PIL\ImageDraw.py", line 253, in text
ink, fill = self._getink(fill)
  File "C:\Python27\ArcGIS10.3\lib\site-packages\PIL\ImageDraw.py", line 129, in _getink
ink = self.palette.getcolor(ink)
  File "C:\Python27\ArcGIS10.3\lib\site-packages\PIL\ImagePalette.py", line 101, in getcolor
self.palette = [int(x) for x in self.palette]
ValueError: invalid literal for int() with base 10: ''
>>> 

問題在於GIF圖片已灰化。 如果先將其轉換為RGB,則代碼將起作用。

換線

img = Image.open(savedFileSA)

img = Image.open(savedFileSA).convert("RGB")

以下是適用於我的計算機的代碼。 它下載一張圖片,並在上面放一個綠色的“示例文本”。 請注意,我在OSX上,因此我的路徑可能與您的不同。

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

urlSA = "http://www.wpc.ncep.noaa.gov/archives/sfc/2015/usfntsfc2015010518.gif"
savedFileSA = "andrew.gif"
urllib.urlretrieve (urlSA, savedFileSA)

img = Image.open(savedFileSA).convert("RGB")
draw = ImageDraw.Draw(img)
fnt = ImageFont.truetype("/Library/Fonts/Comic Sans MS.ttf", 72)
draw.text((10, 10), "Sample Text", (0, 128, 0), font=fnt)

img.show()
img.save("andrew.jpg")

暫無
暫無

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

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