QGIS – How to Import Multiple Raster Files into One GeoPackage

gdal-translategeopackageimportqgisraster

I'm looking for an alternative to import multiple raster files into a GeoPackage other than dragging and dropping via QGIS Browser (sometimes takes to long or returns error).

Following this post I'm using gdal_translate with additional parameters to create a model for exporting a .tif file to an existing GeoPackage without deleting existing tables.

gdal_translate -of GPKG raster_to_import.tif existing.gpkg -co APPEND_SUBDATASET=YES -co RASTER_TABLE=new_table

However, I have problems naming the table based on the input file name when I try to use the batch process as I can't set up a variable for this on command line.

Is there a better alternative using QGIS? Or maybe another way to manage GeoPackage files.

Best Answer

Use the option: 'OPTIONS':'APPEND_SUBDATASET=YES|RASTER_TABLE=raster123', change the raster_table name with each iteration:

import os

newgpkg = '/home/bera/Desktop/all_rasters.gpkg' #Will be created if it doesnt exist
rasterfolder = r'/home/bera/Desktop/GIS/Data/testdata/' #All tif rasters in this folder and all subfolders will be converted

for root, folder, files in os.walk(rasterfolder):
    for file in files:
        if file.endswith('.tif'): #For each tif file in rasterfolder
            print('Processing {0}'.format(file))
            fullname = os.path.join(root, file)
            newname = file.replace('.tif', '_trans') #Adjust this line to change how the output rasters are named
            processing.run("gdal:translate", {'INPUT':fullname,'TARGET_CRS':None,'NODATA':None,
            'COPY_SUBDATASETS':False,'OPTIONS':'APPEND_SUBDATASET=YES|RASTER_TABLE={0}'.format(newname),
            'EXTRA':'','DATA_TYPE':0,'OUTPUT':newgpkg})

enter image description here

Related Question