3

i'm using pyQGis 3 with PyQt5 and i'm trying to render a registred Raster Layer into a file PNG using Python script. The problem is that in the new API they removed QgsMapRender and replaced it with QgsMapSettings and QgsMapRenderJob so i don't know how to render my Raster Layer using command line. in the GUI i just use save map as image and the map will be rendered. How can i do it with command line. here is where i'm stucked.

# create image
img = QImage(QSize(800, 600), QImage.Format_ARGB32_Premultiplied)

# set image's background color
color = QColor(255, 255, 255)
img.fill(color.rgb())

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

render = QgsMapRenderer() #Im stucked Here
#i changed it with 
render=QgsMapSettings() 


# set layer set
 render.setLayers(layer) #here i have a QgsRasterLayer
render.setLayerSet(layer) 

# set extent
rect = QgsRectangle(render.fullExtent())
rect.scale(1.1)
render.setExtent(rect)

# set output size
render.setOutputSize(img.size(), img.logicalDpiX())

# do the rendering
render.render(p)

p.end()

# save image
img.save("render.png","png")
1

You can use QgsMapRendererCustomPainterJob together with QgsMapSettings. QgsMapRendererCustomPainterJob takes the QgsMapSettings and QPainter as parameters and replaces the QgsMapRender that was used previously. You would use QgsMapSettings for the composition details and QPainter for the image creation details.

I have not tested this actual code, but it should be close to correct from your test sample:

# create image
img = QImage(QSize(800, 600), QImage.Format_ARGB32_Premultiplied)

# set image's background color
color = QColor(255, 255, 255)
img.fill(color.rgb())

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

mapSettings = QgsMapSettings() # first create the map settings, then pass to a renderer

# set layer set
mapSettings.setLayers([layer]) # this takes a list of QgsMapLayer as input

# set extent
rect = QgsRectangle(mapSettings.fullExtent())
rect.scale(1.1)
mapSettings.setExtent(rect)

# set output size
mapSettings.setOutputSize(img.size()) # dpi is now set separately (you would use mapsettings.setDpi(), but it's not necessary here)

# do the rendering
render = QgsMapRendererCustomPainterJob(mapSettings, p) # takes the settings and painter as parameters
render.start()             # rendering is now asynchronous, so you could use threads here
render.waitForFinished()   # but we will block until it's finished
p.end()

# save image
img.save("render.png","png")

Your Answer

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

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