from osgeo import gdal, osr, ogr

# 设置数据库连接信息
pg_connection_string = "PG:host=localhost dbname=webgistest user=postgres password=postgres"

# 加载栅格数据
raster_dataset = gdal.Open('D:\gisdata\HEBEI\HebeiDEM.tif')

# 创建PostGIS层
postgis_driver = ogr.GetDriverByName('PostgreSQL')
if postgis_driver is None:
    print("PostGIS 驱动未找到，请确保已安装。")
    exit(1)

# 打开或创建 PostGIS 图层
postgis_layer = postgis_driver.Open(pg_connection_string, update=1)
if postgis_layer is None:
    print("无法连接到 PostGIS 数据库。")
    exit(1)

# 设置空间参考
srs = osr.SpatialReference()
srs.ImportFromWkt(raster_dataset.GetProjectionRef())

# 创建图层
layer_name = 'your_layer_name'
postgis_layer = postgis_layer.CreateLayer(layer_name, srs=srs, geom_type=ogr.wkbPolygon)

# 添加属性
# geom_field = ogr.FieldDefn('geom', ogr.OFTString)
# geom_field.SetWidth(254)  # 设置宽度
# postgis_layer.CreateField(geom_field)

# 设置栅格到 PostGIS
gdal.RasterizeLayer(postgis_layer, [1], raster_dataset.GetLayer(), burnValues=[1])

# 关闭资源
raster_dataset = None
postgis_layer = None
postgis_driver = None