1

Using 3.16.3-Hannover

I have multiple images with a an applied singleband pseudocolor symbology. I'm looking for a way to batch export them. I came across the following code, but it exports the raw data from selected layers, and not the rendered image.

layers = iface.layerTreeView().selectedLayers()
for layer in layers:
    file_name = 'path' + layer.name() + '.tif'
    file_writer = QgsRasterFileWriter(file_name)
    pipe = QgsRasterPipe()
    provider = layer.dataProvider()

    if not pipe.set(provider.clone()):
        print ("Cannot set pipe provider")
        continue
    
    file_writer.Mode(1)
    file_writer.writeRaster(
        pipe,
        provider.xSize(),
        provider.ySize(),
        provider.extent(),
        provider.crs())

1 Answer 1

4

This will export all rasters added to the map as rendered. I want JPEG compression so I added COMPRESS=JPEG

import os

outfolder = r'C:\GIS\data\DEM50m'

for layer in QgsProject.instance().mapLayers().values():
    extent = layer.extent()
    width, height = layer.width(), layer.height()
    renderer = layer.renderer()
    provider=layer.dataProvider()
    crs = layer.crs().toWkt()
    pipe = QgsRasterPipe()
    pipe.set(provider.clone())
    pipe.set(renderer.clone())
    out_file = os.path.join(outfolder, f"{layer.name()}_rendered.tif")
    file_writer = QgsRasterFileWriter(out_file)
    opts = ["COMPRESS=JPEG"]
    file_writer.setCreateOptions(opts)
    file_writer.writeRaster(pipe, width, height, extent, layer.crs())

print('Done')
1
  • 1
    Awesome. I changed the JPEG to LZW. Images are looking good. Thanks!
    – strongium
    Commented Sep 13, 2022 at 15:30

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.