5

I have hundreds of layers. I'd like to be able export each one as a PNG. I can do this by selecting one, and going to project, export map to image, calculate from layer -> select layer -> save. Is there any way I can export all of them as seperate PNG files as a batch process?

I have made progress with the python code below. Unfortunately they are all just white 5k png files.

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

# set background color
color = QColor(255, 255, 255, 255)
img.fill(color.rgba())

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

# create map settings
ms = QgsMapSettings()
ms.setBackgroundColor(color)

# set layers to render
#layer = QgsProject.instance().mapLayersByName('stream_order')
#ms.setLayers([layer[0]])


#get all map layers:

layers = QgsProject.instance().mapLayers().values()

#loop through layers

for layer in layers:

    # set extent
    rect = QgsRectangle(ms.fullExtent())
    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("C:/imageexport/"+layer.name()+".png")

    print('image saved')

replacing rect = QgsRectangle(ms.fullExtent()) with rect = QgsRectangle(layer.extent()) seemed like the logical solution if the issue was the extent being too big, but this just causes QGIS to crash instantly.

I tried the following code and just got a completely black image.

#image_location = os.path.join(QgsProject.instance().homePath(), "render.png")

vlayer = iface.activeLayer()
#vlayer = QgsProject.instance().mapLayersByName("id_")[0]
options = QgsMapSettings()
options.setLayers([vlayer])
options.setBackgroundColor(QColor(255, 255, 255))
options.setOutputSize(QSize(2000, 2000))
options.setExtent(vlayer.extent())

render = QgsMapRendererParallelJob(options)

def finished():
    img = render.renderedImage()
    img.save("C:/Users/smallfing.FINGBIAL/Documents/SHEFFIELD/Road PNG Export/render.png","png")
    #img.save(image_location, "png")
    print("saved")

render.finished.connect(finished)

render.start()
3
  • 1
    To do an automation task this I think you should use PyQGIS.
    – PolyGeo
    Commented Sep 2, 2019 at 21:35
  • Perhaps this answer might help.
    – Joseph
    Commented Sep 3, 2019 at 13:08
  • Thank you for the suggestion. I have tried with some python code (above) but these all come out as blank.
    – James
    Commented Sep 3, 2019 at 19:36

1 Answer 1

0

Try substituting:

render = QgsMapRendererCustomPainterJob(ms, p) 

for:

render = QgsMapRendererParallelJob(ms)

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