Exporting a map as an image removes all of its spatial information. However, you can create an external text file called a world file, which provides the georeferencing information for the raster image, so that it can be used by GIS software, including QGIS, as a raster layer. In this recipe, we'll export a map composition as an image and create a world file with it.
You will need to download the zipped shapefile from https://geospatialpython.googlecode.com/svn/Mississippi.zip and extract it to your qgis_data
directory, to a subdirectory named ms
.
In addition to the shapefile, you will also need the MapComposer
class to simplify the code needed to add this one element. If you have not already used it in a previous recipe, you can download it from https://geospatialpython.googlecode.com/svn/MapComposer.py.
This file must be accessible from the QGIS Python console; for this, you need to ensure that it is in the python path directory. Place the file in the .qgis2/python
directory within your home directory.
First, we'll create the map composition, then we'll save it as an image, and finally we'll generate the world file. To do this, we need to perform the following steps:
from PyQt4.QtCore import * from PyQt4.QtGui import * from qgisfromqgis.core import * from qgisfromqgis.gui import * import MapComposer
lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr") reg = QgsMapLayerRegistry.instance() reg.addMapLayer(lyr) mr = iface.mapCanvas().mapRenderer() qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
output = "/qgis_data/map"
qc.output(output + ".jpg", "jpg")
qc.c.setWorldFileMap(qc.composerMap) qc.c.setGenerateWorldFile(True) wf = qc.c.computeWorldFileParameters()
with open(output + ".jgw", "w") as f: f.write("%s " % wf[0]) f.write("%s " % wf[1]) f.write("%s " % wf[3]) f.write("%s " % wf[4]) f.write("%s " % wf[2]) f.write("%s " % wf[5])
The world file contains the ground distance per pixel and the upper-left coordinate of the map image. The QGIS composer automatically generates this information based on the referenced map. The world file's name must be the same as the image with an extension that uses the first and last letter of the image file extension plus the letter w
. For example, a .TIFF
image file will have a world file with the extension .TFW
. You can learn more about what the world file variables in each line mean at http://en.wikipedia.org/wiki/World_file.