3

I have the following code which batch saves rasters in qgis using the python terminal:

myDir = 'd:/output/'
layers = iface.legendInterface().layers()
pipe = QgsRasterPipe()
for layer in layers:
    extent = layer.extent()
    width, height = layer.width(), layer.height()
    renderer = layer.renderer()
    provider=layer.dataProvider()
    crs = layer.crs().toWkt() 
    pipe.set(provider.clone())
    pipe.set(renderer.clone())
    file_writer = QgsRasterFileWriter(myDir + layer.name() + ".tif")
    file_writer.writeRaster(pipe,
                            width,
                            height,
                            extent,
                            layer.crs())

The tifs that are saved are uncompressed, does anyone know how to turn on compression like LZW?

1

You could try adding the following two lines:

opts = ["COMPRESS=LZW"]     # <== ADD THIS ONE (1)
...
file_writer = QgsRasterFileWriter(myDir + layer.name() + ".tif")
...
file_writer.setCreateOptions(opts)           # <== ADD THIS ONE (2)
...
file_writer.writeRaster(pipe,
                        width,
                        height,
                        extent,
                        layer.crs())

Review of the qgsrasterfilewriter code shows we can pass any of the GDAL raster file creation/manipulation options to the QgsRasterDataProvider class via the setCreateOptions function which accepts a string list (QStringList) of options.

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.