PostGIS  2.4.9dev-r@@SVN_REVISION@@
rtgdalraster.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 #
3 #
4 # A simple utility for passing parameters to ST_AsGDALRaster
5 # for a GDAL raster output
6 # This utility is handy for debugging purposes.
7 #
8 # Example:
9 # rtgdalraster.py -d "dbname=postgres" -r "(SELECT rast FROM pele LIMIT 1)" -f JPEG -o pele.jpg
10 #
11 #
12 
31 from optparse import OptionParser
32 import sys
33 import os
34 import psycopg2
35 
36 def logit(msg):
37  if VERBOSE is True:
38  sys.stderr.write("LOG - " + str(msg) + "\n")
39 
40 
41 try:
42  prs = OptionParser(version="%prog",
43  usage="%prog -d <DB> -r <RASTER> -o <FILE> [-f <FORMAT>] [-c <OPTIONS>]",
44  description="Output raster in a GDAL raster format")
45  prs.add_option("-d", "--db", dest="db", action="store", default=None,
46  help="PostgreSQL database connection string, required")
47  prs.add_option("-r", "--raster", dest="raster", action="store", default=None,
48  help="sql expression to create or access a existing raster, required")
49  prs.add_option("-o", "--output", dest="output", action="store", default=None,
50  help="file to put the output of ST_AsGDALRaster if successful, required")
51  prs.add_option("-f", "--format", dest="format", action="store", default="GTiff",
52  help="format of GDAL raster output, optional, default=GTiff")
53  prs.add_option("-c", "--config", dest="config", action="store", default=None,
54  help="comma separated list of GDAL raster creation options, optional")
55  prs.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
56  help="be excessively verbose and useful for debugging")
57 
58  (opts, args) = prs.parse_args()
59 
60  if opts.db is None:
61  prs.error("use -d option to specify database connection string")
62  if opts.raster is None:
63  prs.error("use -r option to specify a sql expression for a raster")
64  if opts.output is None:
65  prs.error("use -o option to specify raster output file")
66 
67  if opts.config is not None:
68  opts.cfg = opts.config.split(',')
69  else:
70  opts.cfg = None
71 
72  global VERBOSE
73  VERBOSE = opts.verbose
74 
75  conn = psycopg2.connect(opts.db)
76  logit("Connected to %s" % opts.db)
77  logit("Raster expression is %s" % opts.raster)
78 
79  cur = conn.cursor()
80  sql = "SELECT ST_AsGDALRaster(%s, %%s, %%s::text[], NULL::integer)" % (opts.raster)
81  cur.execute(sql, (opts.format, opts.cfg))
82  logit("Number of rows: %i" % cur.rowcount)
83  rec = cur.fetchone()[0];
84  logit("size of raster (bytes): %i" % len(rec))
85 
86  fh = open(opts.output, 'wb', -1)
87  fh.write(rec);
88  fh.flush();
89  fh.close();
90  logit("size of %s (bytes): %i" % (opts.output, os.stat(opts.output)[6]));
91 
92  cur.close();
93  conn.close();
94 
95  print "raster outputted to %s" % opts.output;
96 
97 except Exception, e:
98  print "ERROR: ", e
def logit(msg)
Definition: rtgdalraster.py:36