[GIS] QGis Save Raster as Rendered Image

gdalgdal-translateqgisrasterraster-conversion

In QGIS 1.9.0 Master, when you right click on a raster in the Layers Panel and select "Save As", you can select the output mode to be "Raw Data" or "Renedered Image".

When selecting the Rendered Image option is saves the raster with the layers current styling. How would I do this via the python console? I am able to script gdal_translate, however I am not sure how to preserve the current styling for the layer.

Best Answer

You can do that in Python Console of QGIS by using a QgsRasterPipe object (pipe) for setting a renderer clone of the image employed as active layer before to use the 'writeRaster' method of QgsRasterFileWriter class (you don't need gdal_translate).

I used the following code:

layer = iface.activeLayer()

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())

file_writer = QgsRasterFileWriter('c:/pyqgis_scripts/output2.tif')

file_writer.writeRaster(pipe,
                        width,
                        height,
                        extent,
                        layer.crs())

To test it, I loaded a raster dem (sample_dtm.tif) at the Map Canvas of QGIS and then, it was rendered as a singleband pseudocolor layer with 5 classes (see below image):

enter image description here

After executing the script, the rendered raster (output2.tif) was saved with the espected renderer; as it can be observed in the below image (compare the thumbnails of sample_dtm.tif and output2.tif) when I load output2.tif raster at the Map Canvas. The renderer was effectively cloned in output2.tif raster. The code works.

enter image description here

Related Question