2015-12-02 40 views
0

我有下面的代码下载图像并在图像上写入文本。下载工作正常。该错误发生在draw.text行上。我不知道为什么我得到一个错误。 ttf文件位于正确的位置,路径名正确。我用pip安装枕头。我没有遇到任何错误。使用PIL在图像上添加文字。错误消息

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: '' 
>>> 
+2

您将'.gif'保存为'.jpg',我想这与它有很大关系。 – MattDMo

+0

我改回它保存为一个.gif但仍然得到相同的错误。是的,我相信。 gif图像在文件夹中。 – Andrew

+0

我删除了“(3,3,3)”代码,它工作。也许我需要在我的机器上安装更多的颜色? – Andrew

回答

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") 
+0

啊,谢谢!是的,工作。 – Andrew