Loading raster layer using PyQGIS?

If you keep getting non valid layers, even defining them correctly, you're probably missing the QGIS prefix definition in your script (in case that you work out of QGIS).

qgis_prefix="/usr"    
QgsApplication.setPrefixPath(qgis_prefix, True) 
QgsApplication.initQgis()

If you work on Windows, your qgis_prefix should be something like this:

qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis"

Now your raster layer should be valid.


This code works in my Python Console:

from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo

def StringToRaster(raster):
    # Check if string is provided

    fileInfo = QFileInfo(raster)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()

    layer = QgsRasterLayer(path, baseName)
    QgsMapLayerRegistry.instance().addMapLayer(layer)

    if layer.isValid() is True:
        print "Layer was loaded successfully!"

    else:
        print "Unable to read basename and file path - Your string is probably invalid"

raster = '/home/zeito/Desktop/output2.tif'

StringToRaster(raster)

After running the code in the Python Console of QGIS:

result

For those who will work with QGIS 3:

from qgis.core import QgsRasterLayer
from PyQt5.QtCore import QFileInfo

def StringToRaster(raster):
    # Check if string is provided

    fileInfo = QFileInfo(raster)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()

    layer = QgsRasterLayer(path, baseName)
    QgsProject.instance().addMapLayer(layer)

    if layer.isValid() is True:
        print ("Layer was loaded successfully!")

    else:
        print ("Unable to read basename and file path - Your string is probably invalid")


raster = '/home/zeito/Desktop/output2.tif'

StringToRaster(raster)

Tags:

Pyqgis