[gdal-dev] [GDAL Python] Save a dataset to an in memory Python Bytes object

domlysz domlysz at gmail.com
Wed Aug 10 06:35:19 PDT 2016


Hi all,

I'm trying to use GDAL Python API to save a Numpy array directly to a Python
bytes object in PNG format. Then, bytes data will be pushed as BLOB in a
SQlite database, so I want to avoid using an intermediate file on disk. 

I wish to reproduce something like this snippet with PIL/PILLOW:


b = io.BytesIO()
img = Image.fromarray(data)
img.save(b, format='PNG')
data = b.getvalue() #convert bytesio to bytes


For now I tried to write my Numpy array in a memory dataset:

img_h, img_w, nbBands = data.shape
mem = gdal.GetDriverByName('MEM').Create('', img_w, img_h, nbBands,
gdal.GDT_Byte)
for bandIdx in range(nbBands):
	bandArray = data[:,:,bandIdx]
	mem.GetRasterBand(bandIdx+1).WriteArray(bandArray)

and then save the dataset to a bytes object using the CreateCopy method:

b = io.BytesIO()
out = gdal.GetDriverByName('PNG').CreateCopy(b, mem)

But CreateCopy only accept a valid string path not a bytes object.


I know it's possible to read a bytes stream through a virtual memory file

req = urllib.request.Request(url)
handle = urllib.request.urlopen(req)
data = handle.read()
vsipath = '/vsimem/img'
gdal.FileFromMemBuffer(vsipath, data)
ds = gdal.Open(vsipath)

But I did not find any information on how to do the inverse of this. It's
seems the ReadRaster method return bytes data but if I try to reopen this
output with PIL, it can't recognize the image format.


Any help on this will be very appreciate.

Thanks in advance.


Dominique



--
View this message in context: http://osgeo-org.1560.x6.nabble.com/GDAL-Python-Save-a-dataset-to-an-in-memory-Python-Bytes-object-tp5280254.html
Sent from the GDAL - Dev mailing list archive at Nabble.com.


More information about the gdal-dev mailing list