In order to turn a dynamic GIS map into a static map image or document, you must create a renderer to freeze the map view and create a graphic version of it. In this recipe, we'll render a map to a JPEG image and save it.
You will need to download the following zipped shapefile and extract it to your qgis_data
directory, to a subdirectory named hancock
:
https://geospatialpython.googlecode.com/svn/hancock.zip
You will also need to open the Python Console under the Plugins menu in QGIS. You can run these lines of code inside the console.
In this recipe, we will load our shapefile, add it to the map, create a blank image, set up the map view, render the map image, and save it. To do this, we need to perform the following steps:
Qt
libraries required for image handling:from PyQt4.QtGui import * from PyQt4.QtCore import *
lyr = QgsVectorLayer("/qgis_data/hancock/hancock.shp", "Hancock", "ogr") reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr)
i = QImage(QSize(600,600), QImage.Format_ARGB32_Premultiplied) c = QColor("white") i.fill(c.rgb()) p = QPainter() p.begin(i)
r = QgsMapRenderer()
lyrs = reg.mapLayers().keys()
r.setLayerSet(lyrs)
rect = QgsRectangle(r.fullExtent())
rect.scale(1.1)
r.setExtent(rect)
r.setOutputSize(i.size(), i.logicalDpiX())
r.render(p) p.end()
i.save("/qgis_data/map.jpg","jpg")
qgis_data
directory, similar to the map displayed in QGIS.QGIS uses the underlying Qt GUI library to create common image types. We haven't used any of the QGIS composer objects to render the image; however, this rendering technique is used to save maps created with the QGIS composer.