Skip to content

Commit

Permalink
Merge pull request #1129 from etiennesky/gdaltools_fixes2
Browse files Browse the repository at this point in the history
gdaltools: use GDAL python bindings to get raster SRS and extent (fix #9460)
  • Loading branch information
brushtyler committed Feb 5, 2014
2 parents 6178860 + 4b9e181 commit 58faa5b
Showing 1 changed file with 33 additions and 47 deletions.
80 changes: 33 additions & 47 deletions python/plugins/GdalTools/tools/GdalTools_utils.py
Expand Up @@ -35,7 +35,7 @@
from qgis.core import *
from qgis.gui import *

from osgeo import gdal, ogr
from osgeo import gdal, ogr, osr
from osgeo.gdalconst import *

import os
Expand Down Expand Up @@ -287,59 +287,45 @@ def getVectorFields(vectorFile):

# get raster SRS if possible
def getRasterSRS( parent, fileName ):
processSRS = QProcess( parent )
if ( GdalConfig.versionNum() >= 1900 ):
processSRS.start( "gdalsrsinfo", ["-o", "wkt", "-p", fileName], QIODevice.ReadOnly )
else:
processSRS.start( "gdalinfo", [fileName], QIODevice.ReadOnly )
arr = ''
if processSRS.waitForFinished():
arr = str(processSRS.readAllStandardOutput())
processSRS.close()

if arr == '':
return ''
ds = gdal.Open(fileName)
if ds is None:
return ''

info = arr.splitlines()
if len(info) == 0:
proj = ds.GetProjectionRef()
if proj is None:
return ''

sr = osr.SpatialReference()
if sr.ImportFromWkt(proj) != gdal.CE_None:
return ''

for elem in reversed(info):
m = re.match("^\s*AUTHORITY\[\"([a-z]*[A-Z]*)\",\"(\d*)\"\]", elem)
if m and len(m.groups()) == 2:
return '%s:%s' % (m.group(1), m.group(2))
name = sr.GetAuthorityName(None)
code = sr.GetAuthorityCode(None)
if name is not None and code is not None:
return '%s:%s' % (name,code)

return ''

# get raster extent using python API - replaces old method which parsed gdalinfo output
def getRasterExtent(parent, fileName):
processSRS = QProcess( parent )
processSRS.start( "gdalinfo", [fileName], QIODevice.ReadOnly )
arr = ''
if processSRS.waitForFinished():
arr = str(processSRS.readAllStandardOutput())
processSRS.close()

if arr == '':
return

ulCoord = lrCoord = ''
xUL = yLR = xLR = yUL = 0
info = arr.splitlines()
for elem in info:
m = re.match("^Upper\sLeft.*", elem)
if m:
ulCoord = m.group(0).strip()
ulCoord = ulCoord[string.find(ulCoord,"(") + 1 : string.find(ulCoord,")") - 1].split( "," )
xUL = float(ulCoord[0])
yUL = float(ulCoord[1])
continue
m = re.match("^Lower\sRight.*", elem)
if m:
lrCoord = m.group(0).strip()
lrCoord = lrCoord[string.find(lrCoord,"(") + 1 : string.find(lrCoord,")") - 1].split( "," )
xLR = float(lrCoord[0])
yLR = float(lrCoord[1])
continue
ds = gdal.Open(fileName)
if ds is None:
return

x = ds.RasterXSize
y = ds.RasterYSize

gt = ds.GetGeoTransform()
if gt is None:
xUL = 0
yUL = 0
xLR = x
yLR = y
else:
xUL = gt[0]
yUL = gt[3]
xLR = gt[0] + gt[1]*x + gt[2]*y
yLR = gt[3] + gt[4]*x + gt[5]*y

return QgsRectangle( xUL, yLR, xLR, yUL )

Expand Down

0 comments on commit 58faa5b

Please sign in to comment.