6

How to add layers (vector or raster to an existing GeoPackage)?

While loading an existing layer of a GeoPackage is quite trivial:

path = '/home/matteo/geopackage.gpkg|layername={}'.format('admin')
iface.addVectorLayer(path, 'admin', 'ogr')

I couldn't find information about adding them via PyQGIS.

Is it possible? Will it also work for rasters?

5

You need to use QgsVectorFileWriter.writeAsVectorFormat. If you store one layer per GPKG file you just need:

# get layer list by one of:
lyrs = iface.mapCanvas().layers() # OR
lyrs = QgsMapLayerRegistry.instance().mapLayers() # OR
lyrs = iface.layerTreeView().selectedLayers()

# select layer
lyr = lyrs[0]
_writer = QgsVectorFileWriter.writeAsVectorFormat(lyr, r"C:\gisData\layer.gpkg")

If you want save more than one layer in gkpg file you should set additional options.

for lyr in filter(lambda l: l.type() == QgsMapLayer.VectorLayer, lyrs):
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer 
    options.layerName = "_".join(lyr.name().split(' '))
    _writer = QgsVectorFileWriter.writeAsVectorFormat(lyr, gpkgPath, options)
    if _writer:
        print(lyr.name(), _writer)

PyQGIS should have similar interface for raster layers. In my opinion easiest way to find out is to install IPyConsole plugin and use PyQGIS API

  • QgsMapLayerRegistry is gone in QGIS 3, but writeAsVectorFormat should still be there. Sidenote, there is also the QgsVectorLayerExporter class available. – Matthias Kuhn Nov 2 '18 at 7:38
3

I have investigated this code an create a script like it works very well for exporting raster layer to geopackage:

ds = ogr.Open(self.projectGpkg, True)
source = QgsRasterLayer(layerSource, 'rasterLayer', 'gdal')
if source.isValid():
    provider = source.dataProvider()
    fw = QgsRasterFileWriter(self.projectGpkg)
    fw.setOutputFormat('gpkg')
    fw.setCreateOptions(["RASTER_TABLE=" + str(tableName), 'APPEND_SUBDATASET=YES'])

    pipe = QgsRasterPipe()
    if pipe.set(provider.clone()) is True:
        projector = QgsRasterProjector()
        projector.setCrs(provider.crs(), provider.crs())
        if pipe.insert(2, projector) is True:
            if fw.writeRaster(pipe, provider.xSize(),provider.ySize(),provider.extent(),provider.crs()) == 0:
                print("ok")
            else:
                print("error")
ds = None

For reading raster layer in geopackage:

rlayer = QgsRasterLayer('GPKG:' + str(self.projectGpkg) + ':tableName', "layerName")

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.