Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

Any help would be much appreciated.

Regards Gavin

share|improve this question
    
Does anyone have an answer for this? –  Tom Chadwin Apr 14 at 17:02
    
@Tom Chadwin You have an answer. –  xunilk Apr 17 at 19:21

1 Answer 1

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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