0

Using the QGIS application, I am able to do this. However, I am unsure of how to do it using Python.

I have this so far:

from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import time
import sys

def main():
    qgis_prefix="/usr"    
    QgsApplication.setPrefixPath(qgis_prefix, True) 
    app = QgsApplication([], True)
    app.initQgis()

    canvas = QgsMapCanvas()
    canvas.setCanvasColor(Qt.white)

    fileName = "/..."
    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    path = fileInfo.filePath()
    rlayer = QgsRasterLayer(path, baseName)
    if not rlayer.isValid():
            print "Layer is not valid!"
    QgsMapLayerRegistry.instance().addMapLayer(rlayer)
    canvas.setExtent(rlayer.extent())
    canvas.setLayerSet([QgsMapCanvasLayer(rlayer)])

    canvas.refresh()
    app.exec_()
    app.exitQgis()
main()

Also, I can't get this program to terminate without manually doing it.

1

You can add the following line after canvas.setLayerSet([QgsMapCanvasLayer(rlayer)]) to save the canvas as a png file:

canvas.saveAsImage("path/to/image.png")

You can also try closing the application using sys.exit().


So your code could look like:

from qgis.gui import *
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, time

def main():
    qgis_prefix="/usr"    
    QgsApplication.setPrefixPath(qgis_prefix, True) 
    app = QgsApplication([], True)
    app.initQgis()

    canvas = QgsMapCanvas()
    canvas.setCanvasColor(Qt.white)

    fileName = "/..."
    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    path = fileInfo.filePath()
    rlayer = QgsRasterLayer(path, baseName)
    if not rlayer.isValid():
        print "Layer is not valid!"
    QgsMapLayerRegistry.instance().addMapLayer(rlayer)
    canvas.setExtent(rlayer.extent())
    canvas.setLayerSet([QgsMapCanvasLayer(rlayer)])
    # Save canvas as image
    canvas.saveAsImage("path/to/image.png")

    canvas.refresh()
    app.exec_()
    app.exitQgis()
    sys.exit()    
main()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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