Skip to content

Commit ead220e

Browse files
authored
Add caching to arcgisimage
arcgisimageis slow due to network communication, especially when you are working with high-resolution plots of the same region. This commit adds a cachedir to the arcgisimage function, to prevent downloading the same image multiple times.
1 parent f37aed3 commit ead220e

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
@@ -4217,7 +4217,7 @@ def warpimage(self,image="bluemarble",scale=None,**kwargs):
42174217

42184218
def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
42194219
service='World_Imagery',xpixels=400,ypixels=None,\
4220-
dpi=96,verbose=False,**kwargs):
4220+
dpi=96,cachedir=None,verbose=False,**kwargs):
42214221
"""
42224222
Retrieve an image using the ArcGIS Server REST API and display it on
42234223
the map. In order to use this method, the Basemap instance must be
@@ -4243,6 +4243,7 @@ def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
42434243
map projection region.
42444244
dpi The device resolution of the exported image (dots per
42454245
inch, default 96).
4246+
cachedir An optional directory to use as cache folder for the retrieved images.
42464247
verbose if True, print URL used to retrieve image (default
42474248
False).
42484249
============== ====================================================
@@ -4302,8 +4303,31 @@ def arcgisimage(self,server='http://server.arcgisonline.com/ArcGIS',\
43024303
(server,service,xmin,ymin,xmax,ymax,self.epsg,self.epsg,xpixels,ypixels,dpi)
43034304
# print URL?
43044305
if verbose: print(basemap_url)
4306+
4307+
if cachedir != None:
4308+
# Generate a filename for the cached file.
4309+
filename = "%s-bbox-%s-%s-%s-%s-bboxsr%s-imagesr%s-size-%s-%s-dpi%s.png" %\
4310+
(service,xmin,ymin,xmax,ymax,self.epsg,self.epsg,xpixels,ypixels,dpi)
4311+
4312+
# Check if the cache directory exists, if not create it.
4313+
if not os.path.exists(cachedir):
4314+
os.makedirs(cachedir)
4315+
4316+
# Check if the image is already in the cachedir folder.
4317+
cache_path = cachedir + filename
4318+
4319+
if os.path.isfile(cache_path):
4320+
print('Image already in cache')
4321+
img = Image.open(cache_path)
4322+
return basemap.imshow(img, ax=ax, origin='upper')
4323+
else:
4324+
# Retrieve and save image
4325+
img = Image.open(urlopen(basemap_url))
4326+
img.save(cache_path)
4327+
else:
4328+
img = Image.open(urlopen(basemap_url))
4329+
43054330
# return AxesImage instance.
4306-
img = Image.open(urlopen(basemap_url))
43074331
return self.imshow(img, ax=ax, origin='upper')
43084332

43094333
def wmsimage(self,server,\

0 commit comments

Comments
 (0)