繁体   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