i want to try to add raster layers(.tif) in QGIS using pyqgis first in python console first and after in the new QGIS plugin but i am very confused with that and specific to add tif rasters layers. i use QGIS 2.6.1 (and i test all in QGIS 2.18.3 but i need 2.6.1 version) and python 2.7.13 in windows 10 or 7.
first i try this code from this post:
from qgis.core import QgsRasterLayer
from PyQt4.QtCore import QFileInfo
def StringToRaster(raster):
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 = '/path/to/raster/file.tif'
StringToRaster(raster)
that not working for me with all rasters ".tif,.jpg,.png"
error :
Unable to read basename and file path - Your string is probably invalid
if i try this from official QGIS tutorial post:
fileName = "/path/to/raster/file.tif"
fileInfo = QFileInfo(fileName)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(fileName, baseName)
if not rlayer.isValid():
print "Layer failed to load!"
that working only with ".jpg" and ".png" but not for ".tif" rasters layers
error :
"Layer failed to load!"
and finaly i test this :
iface.addRasterLayer("/path/to/raster/file.tif", "layer name you like")
and i take that error message if i want to add .tif raster(other raster i can add with this method):
Cannot open GDAL dataset
`/path/to/raster/file.tif': does not exist in the file system,
and is not recognised as a supported dataset name.
and finaly i test this code from this post
import osgeo.gdal
from gdalconst import *
from PyQt4.QtCore import QFileInfo,QSettings
from qgis.core import QgsRasterLayer, QgsCoordinateReferenceSystem
file = QFileDialog.getOpenFileName(self,
"Open TIF Image", ".", "Tagged image (*.tif)")
fileInfo = QFileInfo(file)
fileName=fileInfo.fileName()
baseName = fileInfo.baseName()
layer = QgsRasterLayer(file, baseName)
error :
no module name gdalconst
that is the bug or QGIS or i do something wrong ?
'QFileDialog' is not defined– Chris Papas Mar 17 '17 at 21:46from PyQt4.QtGui import QFileDialogwhich should remove the name error. – Joseph Mar 20 '17 at 10:07