In case somebody needs to do the buffering of geometries (using pure OGR).
I am trying to create reduced/extended polygons from an existing polygon using OGR in Python.
More precisely I want to create a buffer with negative/positive distance and based on that create a new polygon with borders drawn inward/outward.
For this I used Create Buffer from GDAL/OGR cookbook as the template with a small addition of importing SRS from the input polygon to the output(buffer) polygon.
I have been suggested to use SQLite dialect in order to achieve it. This means that there are certainly more options to get the same results.
Here is the code:
import os import sys from osgeo import ogr from osgeo import osr def createBuffer(inputfn, outputBufferfn, bufferDist): inputds = ogr.Open(inputfn) inputlyr = inputds.GetLayer() shpdriver = ogr.GetDriverByName('ESRI Shapefile') if os.path.exists(outputBufferfn): shpdriver.DeleteDataSource(outputBufferfn) outputBufferds = shpdriver.CreateDataSource(outputBufferfn) # create the spatial reference system, WGS84 #srs = osr.SpatialReference() #srs.ImportFromEPSG(4326) srs = inputlyr.GetSpatialRef() bufferlyr = outputBufferds.CreateLayer(outputBufferfn,srs, geom_type=ogr.wkbPolygon) featureDefn = bufferlyr.GetLayerDefn() for feature in inputlyr: ingeom = feature.GetGeometryRef() geomBuffer = ingeom.Buffer(bufferDist) outFeature = ogr.Feature(featureDefn) outFeature.SetGeometry(geomBuffer) bufferlyr.CreateFeature(outFeature) outFeature = None def main(inputfn, outputBufferfn, bufferDist): createBuffer(inputfn, outputBufferfn, bufferDist) if __name__ == "__main__": inputfn = 'polygon.shp' outputBufferfn = 'polygonBuffer.shp' bufferDist = -1.0 main(inputfn, outputBufferfn, bufferDist)