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!")
project.addMapLayer(layer)
return layer
def openTemplate(layout, templatePath):
template = open(templatePath, 'rt')
content = template.read()
template.close()
doc = QDomDocument()
doc.setContent(content)
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)
QGS.initQgis()
# create project & layout
project = QgsProject()
layout = QgsPrintLayout(project)
layout.initializeDefaults()
# 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
gdal.PushErrorHandler('CPLQuietErrorHandler')
But I rather not have to.