Search code examples
pythonpnggdal

How to save data to PNG using GDAL


I am trying to save data to a PNG. The file is created (and dimensions are correct, however the data is not written to it.

Minimal example code:

from osgeo import gdal
import numpy as np

# data:
filename = '/tmp/test.png'
nx = 512
ny = 512
n_bands = 3
datatype = gdal.GDT_Byte

# create destination:
dst_driver_tmp = gdal.GetDriverByName('MEM')
dst_tmp = dst_driver_tmp.Create('', xsize=nx, ysize=ny, bands=n_bands, eType=datatype)
dst_driver = gdal.GetDriverByName('PNG')
dst_ds = dst_driver.CreateCopy(filename, dst_tmp, strict=0)
if not dst_ds:
    raise Exception("CreateCopy failed")

# write data:
for i in range(n_bands):
    data = np.array([[i * 0.5]])
    band = dst_ds.GetRasterBand(i + 1).WriteArray(data)

dst_ds.FlushCache()
dst_ds = None

Running this code produces errors:

ERROR 6: /tmp/test.png, band 1: WriteBlock() not supported for this dataset.
ERROR 6: /tmp/test.png, band 2: WriteBlock() not supported for this dataset.
ERROR 6: /tmp/test.png, band 3: WriteBlock() not supported for this dataset.

The file is created and is a valid PNG file, but the image is black.

I have tried changing eType, using different values, dimensions, number of bands... no difference. If it matters:

$ gdalinfo --version
GDAL 2.2.2, released 2017/09/15
$ gdalinfo --formats | grep PNG
  PNG -raster- (rwv): Portable Network Graphics

Any idea how I can write values to a PNG using GDAL?


Solution

  • It turns out I misunderstood the role of CreateCopy. Data needs to be written to dst_tmp, and then CreateCopy is simply called at the end to create the PNG file in a single step. Hope it helps someone.