GDAL – How to Use the Parameter from gdal_rasterize

gdalgdal-rasterizeogr

I'm using the following command to generate a TIFF file from a shapefile:

gdal_rasterize -burn 255 -burn 0 -burn 0 -ot Byte -tr 0.0000169959 0.0000169959 -l layer_name input.shp output.tif

It works fine, but I'd like to use it with a GeoJSON file as input as well… On the gdal_rasterize documention it says that I can use any OGR supported readable datasource, so it should accept GeoJSON files as input as well… I didn't understand how I should be using the <src_datasource> option. I've tried putting a GeoJSON file on the command directly as follows:

gdal_rasterize -burn 255 -burn 0 -burn 0 -ot Byte -tr 0.0000169959 0.0000169959 -l layer_name input.geojson output.tif

But I got the error:

ERROR 1: Attempt to create -2147483648x-2147483648 dataset is illegal,sizes must be larger than zero.
ERROR 1: Cannot create output.tif

I've also tried writing GeoJSON on the command:

gdal_rasterize -burn 255 -burn 0 -burn 0 -ot Byte -tr 0.0000169959 0.0000169959 -GeoJSON -l layer_name input.geojson output.tif

And I got the error:

ERROR 6: Too many command options 'output.tif'

What am I getting wrong? How can I use the OGR supported formats with gdal_rasterize?

Best Answer

In your original command options

-l input input.shp

the input.shp is the datasource and input is the layer of the datasource that will be used. If the datastore can contain many layers, or if the name of the layer is not known directly the desired layer can be selected with option -l. Shapefile can have only one layer and the name of the layer is the same than the name of the datastore and GDAL knows it. Therefore the -l inputin your original command is unnecessary. The documentation https://gdal.org/programs/gdal_rasterize.html is not quite clear about the fact that -l in not always needed.

GeoJSON can also have only one layer and GDAL knows that. You can use a command that is as simple as this:

gdal_rasterize -burn 255 -burn 0 -burn 0 -ot Byte -tr 0.0000169959 0.0000169959 input.geojson output.tif

If you for some reason want to use the -l option with a GeoJSON file it is not as simple as with a shapefile because the layer name in GeoJSON can be something else than the file name. You can check what the layer name is with ogrinfo. In this example the name of the layer is out.

ogrinfo myPolygonizedImage.geojson
INFO: Open of `myPolygonizedImage.geojson'
      using driver `GeoJSON' successful.
1: out (Polygon)