Skip to content

Instantly share code, notes, and snippets.

@davidvhill
Forked from jleinonen/gdal_mmap.py
Last active July 14, 2016 18:31
Show Gist options
  • Save davidvhill/345025c5c16b6a3277ee83ed83a43fce to your computer and use it in GitHub Desktop.
Save davidvhill/345025c5c16b6a3277ee83ed83a43fce to your computer and use it in GitHub Desktop.
GDAL in memory results
# also: https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html#load-data-to-memory
# another, maybe better approach to this is to use the gdal 'MEM' driver and then use
# sds.ReadRaster() and sds.WriteRaster() to get at the bytes.
# >>> from osgeo import gdal
# >>> driver = gdal.GetDriverByName('MEM')
# >>> sds = driver.Create('', 200, 300, 4)
# >>> sds.ReadRaster()
# If specifying gzip encoding and transferring the image results via body this way,
# metadata + projection information will still be needed. Easiest to stash these in
# the HTTP headers because ReadRaster() is the byte representation of ReadAsArray().
from gzip import GzipFile
from io import BytesIO
import urllib2
from uuid import uuid4
import gdal
def open_http_query(url):
try:
request = urllib2.Request(url,
headers={"Accept-Encoding": "gzip"})
response = urllib2.urlopen(request, timeout=30)
if response.info().get('Content-Encoding') == 'gzip':
return GzipFile(fileobj=BytesIO(response.read()))
else:
return response
except urllib2.URLError:
return None
def open_image(url):
image_data = open_http_query(url)
if not image_data:
return None
mmap_name = "/vsimem/"+uuid4().get_hex()
gdal.FileFromMemBuffer(mmap_name, image_data.read())
gdal_dataset = gdal.Open(mmap_name)
image = gdal_dataset.GetRasterBand(1).ReadAsArray()
gdal_dataset = None
gdal.Unlink(mmap_name)
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment