[GIS] Save raster layers in a python script

pyqgisqgisraster

Is there a way to loop through every selected layer in qgis and save it as a .tif file with the same layer name using a python script?

This is the code I am using, but it does nothing at all. It runs but does nothing.

Can someone help me?

from PyQt4.QtCore import *
from qgis.core import *
from qgis.gui import *
import os
import sys


layers = iface.layerTreeView().selectedLayers()
for layer in layers:
    output='Desktop'%layer.name%'.tif'
shareeditundeleteflag

Best Answer

I guess thoses layers are all rasters to begin with. You could find a way by importing qgis core and processing inside a Python shell. By doing this you can extract the selected items from qgis. For the processing afterwards you could use the gdal merge tool as if you were running an algorythm or calling a function. I must have a python code where i did something like this somewhere i think.

EDIT: Ok so the Python importing and initialization of the whole code should be something like this:

import os
import sys
from qgis.core import *
qgis.path.insert(0, 'C:\OSGeo4W64\apps\qgis\python')
from PyQt4.QtGui import *
app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()

You'll need the sys and OS modules for what you want to do, almost 100%. If you want to import the processing tools from qgis it'll be something like this:

# Prepare processing framework 
sys.path.append('C:\OSGeo4W64\apps\qgis\python\plugins')
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

That'll import the whole toolbox, for running tools just use the general.runalg('your tool name', 'data in', 'data ou') prompt, you'll need to look for the tool's name and options beforhand inside the python console built in qgis.

Related Question