I am trying to export a .tif loaded into a pre-configured print layout template and further exported as .png

def openLayer(project, fp, basename, vector=True):
  layer = QgsVectorLayer(fp, basename) if vector else QgsRasterLayer(fp, basename)
  if not layer.isValid():
    print("Layer failed to load!")

  return layer

def openTemplate(layout, templatePath):
  template = open(templatePath, 'rt')
  content = template.read()
  doc = QDomDocument()
  context = QgsReadWriteContext()
  if not layout.loadFromTemplate(doc, context):
    print('unable to load template: {}'.format(templatePath))

def export(layout, dest, filename):
  dest = os.path.join(dest, filename + '.png') #FIXME: set filetype in config
  export = QgsLayoutExporter(layout)
  export.exportToImage(dest, QgsLayoutExporter.ImageExportSettings())

# initialize
QGS = QgsApplication([], False)

# create project & layout
project = QgsProject()
layout = QgsPrintLayout(project)

# load layers
baseLayer = openLayer(project, r'C:\Users\X\Desktop\atlas\ar_base.tif', 'ar_base', vector=False)

# open template
openTemplate(layout, r'C:\Users\X\Desktop\atlas\test.qpt')

# export
print('exporting . . .')
export(layout, r'C:\Users\X\Desktop\atlas', 'test')

The snippet successfully creates a .png with the image inside. However I get the following error:

ERROR 6: The PNG driver does not support update access to existing datasets.

Would anyone know why that is? I wasn't able to find a concrete answer by searching unfortunately.

EDIT: seems related to the PNG GDAL driver. However, there is no updating within this process but simply creation.

I can suppress the error / warning via:

from osgeo import gdal

But I rather not have to.

  • Same issue indeed. I will keep this in mind.
    – etrimaille
    Nov 15, 2021 at 19:08
  • Same issue indeed. I also will keep this in mind.
    – RBenet
    Dec 21, 2021 at 8:05


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.