简体   繁体   English

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

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

I have the following code that downloads an image and writes text on the image. 我有以下代码,可以下载图像并在图像上写入文本。 The download works fine. 下载工作正常。 The error occurs on the draw.text line. 错误发生在draw.text行上。 I'm not sure why I am getting an error. 我不确定为什么会出错。 The ttf file is in the correct location and pathname is correct. ttf文件位于正确的位置,并且路径名正确。 I installed Pillow using pip. 我使用pip安装了Pillow。 I didn't come across any errors with it. 我没有遇到任何错误。

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)

Error: 错误:

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

The problem is that the GIF picture is palettized. 问题在于GIF图片已灰化。 If you convert it first to RGB, your code will work. 如果先将其转换为RGB,则代码将起作用。

Change the line 换线

img = Image.open(savedFileSA)

to

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

Below is the code that works on my machine. 以下是适用于我的计算机的代码。 It downloads a picture and put a big green 'Sample Text' on it. 它下载一张图片,并在上面放一个绿色的“示例文本”。 Note that I'm on OSX, so my paths may differ from yours. 请注意,我在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