7

I have a transparent raster on top of a hillshade.

I want to Project - Import/Export - Export map to image using PyQGIS:

enter image description here

I need to be able to set extent, scale, dpi and the output needs to be georeferenced.

I have followed PyQGIS: Render (Print/Save) a Layer as an Image to get an output but the output has no coordinate system set.

How can I export the image including this?

img = QImage(QSize(3000, 3000), QImage.Format_ARGB32_Premultiplied)
img.setDotsPerMeterX(1)
img.setDotsPerMeterY(1)

# create map settings
ms = QgsMapSettings()

# create painter
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)

# set layers to render
layers = list(reversed([lyr for lyr in QgsProject.instance().mapLayers().values()]))
ms.setLayers(layers)

# set extent
rect = iface.mapCanvas().extent()
rect.scale(1.1)
ms.setExtent(rect)

# set ouptut size
ms.setOutputSize(img.size())

# setup qgis map renderer
render = QgsMapRendererCustomPainterJob(ms, p)
render.start()
render.waitForFinished()
p.end()

# save the image
img.save('/home/bera/Desktop/test_render.png')

print('Done')

1 Answer 1

7

You can create an external world file, which provides the georeferencing information for the raster image you export.

...

# save the image
img.save('/home/bera/Desktop/test_render.png')

# world file content
pgw_content = QgsMapSettingsUtils.worldFileContent(ms)

with open('/home/bera/Desktop/test_render.pgw', "w") as f:
    f.write(pgw_content)

print('Done')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.