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. I'm not sure why I am getting an error. The ttf file is in the correct location and pathname is correct. I installed Pillow using pip. 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. If you convert it first to RGB, your code will work.
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.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.