使用 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")

下面是在我的机器上运行的代码。它下载了一张图片并在上面放了一个大大的绿色'Sample Text'。请注意,我在 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")