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")