GoogleEarth is one of the most widely available geospatial viewers in existence. The XML data format used by GoogleEarth for geospatial data is called KML. The Open Geospatial Consortium adopted KML as a data standard. Converting rasters into a KML overlay compressed in a KMZ archive file is a very popular way to make data available to end users who know how to use GoogleEarth.
We will use the SatImage raster again available at the following URL if you haven't downloaded it from previous recipes:
https://geospatialpython.googlecode.com/files/SatImage.zip
Place this raster in your /qgis_data/rasters
directory.
In this recipe, we'll create a KML document describing our image. Then we'll convert the image to a JPEG in memory using GDAL's specialized virtual file system and write all of the contents directly to a KMZ file using Python's zipfile
module.
gdal
module as well as the Python zipfile
module:from osgeo import gdal import zipfile
gdal
:srcf = "/qgis_data/rasters/Satimage.tif"
vismem
:vfn = "/vsimem/satimage.jpg"
drv = gdal.GetDriverByName('JPEG')
src = gdal.Open(srcf)
tgt = drv.CreateCopy(vfn, src)
rasterLyr = QgsRasterLayer(srcf, "SatImage")
e = rasterLyr.extent()
kml = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name>QGIS KML Example</name> <GroundOverlay> <name>SatImage</name> <drawOrder>30</drawOrder> <Icon> <href>SatImage.jpg</href> </Icon> <LatLonBox> <north>%s</north> <south>%s</south> <east>%s</east> <west>%s</west> </LatLonBox> </GroundOverlay> </Document> </kml>""" %(e.yMaximum(), e.yMinimum(), e.xMaximum(), e.xMinimum())
vsifile = gdal.VSIFOpenL(vfn,'r') gdal.VSIFSeekL(vsifile, 0, 2) vsileng = gdal.VSIFTellL(vsifile) gdal.VSIFSeekL(vsifile, 0, 0)
z = zipfile.ZipFile("/qgis_data/rasters/satimage.kmz", "w", zipfile.ZIP_DEFLATED) z.writestr("doc.kml", kml) z.writestr("SatImage.jpg", gdal.VSIFReadL(1, vsileng, vsifile)) z.close()
KML is a straightforward XML format. There are entire libraries in Python dedicated to reading and writing it, but for a simple export to share an image or two, the PyQGIS console is more than adequate. While we run this script in the QGIS Python interpreter, it could be run outside of QGIS using just GDAL.