2

As per the suggestions given by Michael to one of my earlier query (URL given below), I have tried to develop a sample code to perform rasterize using GDAL Java API methods. I had written based on the Python sample from cookbook.

https://gis.stackexchange.com/questions/305164/using-gdal-proximity-function?noredirect=1#comment498883_305164

I am performing rasterize on a shapefile and the above code generates output but image in blank.

publicpublic void rasterizeShp() {

    //# Define pixel_size and NoData value of new raster
    int pixel_size = 25;
    int NoData_value = 255;

    gdal.AllRegister();
    org.gdal.ogr.ogr.RegisterAll();
    int bufferDistance = 20;

    String shpFilePath = "C:/img/GLXMABufferRadius.shp";

    //# Open the data source and read in the extent
    DataSource sourceDs = org.gdal.ogr.ogr.Open(shpFilePath,gdalconstConstants.GA_ReadOnly);
    Layer sourceLayer = sourceDs.GetLayer(0);

    SpatialReference sourceSrs = sourceLayer.GetSpatialRef();
    double[] extent = sourceLayer.GetExtent();

    //# Create the destination data source
    double x_res = ((extent[1] - extent[0]) / pixel_size);
    double y_res = ((extent[3] - extent[2]) / pixel_size);
    System.out.println("x_res -------" + x_res +  "y " + y_res );
    int xCor = (int)x_res;
    int yCor = (int)y_res;

    System.out.println("xCor -------" + xCor);
    System.out.println("yCor -------" + yCor);

    String output = "C:/img/myAttrOp2.tif";
    org.gdal.gdal.Dataset target_ds = gdal.GetDriverByName("GTiff").Create(output, xCor, yCor, 1, gdalconst.GDT_Byte);
    target_ds.SetGeoTransform(new double[]{extent[0], pixel_size, 0, extent[2], 0, -pixel_size});
    //target_ds.SetGeoTransform(sourceLayer.GetExtent());
    Band band = target_ds.GetRasterBand(1);
    band.SetNoDataValue(NoData_value);
    band.FlushCache();

    int[] intArr = {1};

    //# Rasterize
    gdal.RasterizeLayer(target_ds, intArr, sourceLayer, null);

}

Is this the right approach for rasterizing. Also I would like to know the correct way of setting geotransform. I sometimes get "ERROR 1: Attempt to create 2x0 dataset is illegal, sizes must be larger than zero".

Please let me know if there are corrections to be made in the below code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.