Skip to content

Commit d669ff0

Browse files
authored
Merge pull request #562 from JoepdeJong/patch-1
Add caching to Basemap.arcgisimage
2 parents e58ceca + ead220e commit d669ff0

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

packages/basemap/src/mpl_toolkits/basemap/__init__.py

+26-2
Original file line numberDiff line numberDiff line change
@@ -4222,7 +4222,7 @@ def warpimage(self,image="bluemarble",scale=None,**kwargs):
42224222

42234223
def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
42244224
service='World_Imagery',xpixels=400,ypixels=None,\
4225-
dpi=96,verbose=False,**kwargs):
4225+
dpi=96,cachedir=None,verbose=False,**kwargs):
42264226
"""
42274227
Retrieve an image using the ArcGIS Server REST API and display it on
42284228
the map. In order to use this method, the Basemap instance must be
@@ -4248,6 +4248,7 @@ def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
42484248
map projection region.
42494249
dpi The device resolution of the exported image (dots per
42504250
inch, default 96).
4251+
cachedir An optional directory to use as cache folder for the retrieved images.
42514252
verbose if True, print URL used to retrieve image (default
42524253
False).
42534254
============== ====================================================
@@ -4307,8 +4308,31 @@ def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
43074308
(server,service,xmin,ymin,xmax,ymax,self.epsg,self.epsg,xpixels,ypixels,dpi)
43084309
# print URL?
43094310
if verbose: print(basemap_url)
4311+
4312+
if cachedir != None:
4313+
# Generate a filename for the cached file.
4314+
filename = "%s-bbox-%s-%s-%s-%s-bboxsr%s-imagesr%s-size-%s-%s-dpi%s.png" %\
4315+
(service,xmin,ymin,xmax,ymax,self.epsg,self.epsg,xpixels,ypixels,dpi)
4316+
4317+
# Check if the cache directory exists, if not create it.
4318+
if not os.path.exists(cachedir):
4319+
os.makedirs(cachedir)
4320+
4321+
# Check if the image is already in the cachedir folder.
4322+
cache_path = cachedir + filename
4323+
4324+
if os.path.isfile(cache_path):
4325+
print('Image already in cache')
4326+
img = Image.open(cache_path)
4327+
return basemap.imshow(img, ax=ax, origin='upper')
4328+
else:
4329+
# Retrieve and save image
4330+
img = Image.open(urlopen(basemap_url))
4331+
img.save(cache_path)
4332+
else:
4333+
img = Image.open(urlopen(basemap_url))
4334+
43104335
# return AxesImage instance.
4311-
img = Image.open(urlopen(basemap_url))
43124336
return self.imshow(img, ax=ax, origin='upper')
43134337

43144338
def wmsimage(self,server,\

0 commit comments

Comments
 (0)