I have a Multipolygon layer in a PostGIS database which essentially makes a gridded data field.

I want to clip this data using a bounding box and the clipped data should include all the polygons with which the bounding box intersects. This I can do with the following code:

import psycopg
conn = psycopg.connect(dbname = db, user = username, password = passp, host = host_ad, sslmode = "prefer")

with conn.cursor() as cur:
    sql  = "SELECT * FROM WHERE shape && ST_GeomFromText('SRID=25832;POLYGON(({} {}, {} {}, {} {}, {} {}, {} {} ))')".format(inlayer, minx, miny, maxx, miny, maxx, maxy, minx, maxy, minx, miny)

Once the data has been clipped, how can I rasterize the data and export it as a multiband GeoTIFF where each field is saved in a different band?

1 Answer 1


Use st_asraster - docs - chained with st_asgdalraster - docs.

SELECT ST_AsGDALRaster(rast, 'GTiff') As rastgtiff
from (select ST_AsRaster(
            ST_GeomFromText('LINESTRING(50 50,150 150,150 50)'), 10,'join=bevel'),
            200,200,ARRAY['8BUI', '8BUI', '8BUI'], ARRAY[118,154,118], ARRAY[0,0,0]) rast
      ) foo;

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.