使用PIL在图像上添加文本。错误信息

时间:2015-12-02 20:45:48

标签: python python-imaging-library

我有以下代码可下载图像并在图像上写入文字。下载工作正常。 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: ''
>>> 

1 个答案:

答案 0 :(得分:2)

问题是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")