Erik Juríček
Erik Juríček

Reputation: 75

Java Geotools Tiff Data Fields extract

I have Tiff file of population density in the world from Sadac.

I try to read this file in java and extract density number for specific point (LatLon). I tried opening and reading the file with Geotools, but i dont know, how to extract specific point and its fields (density). I tried many ways but none of them worked.

My code actualy:

File f = new File("/opt/gpw-v4-population-density_2020.tif");
    AbstractGridFormat format = GridFormatFinder.findFormat(f);

    AbstractGridCoverage2DReader reader = format.getReader(f);

    CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
    System.out.println(crs);

    GridCoverage2D cov = null;
    try {
        cov = reader.read(null);
    } catch (Exception e) {
        //todo
    }

Can anyone advise me how to get to the point and its fields? Thank you for advice.

Upvotes: 0

Views: 174

Answers (1)

Erik Juríček
Erik Juríček

Reputation: 75

Resolved.

private static GridCoverage2D grid;
private static Raster gridData;

     private static void initTif() throws Exception {
        File tiffFile = new File("/opt/gpw-v4-population-density_2020.tif");
        GeoTiffReader reader = new GeoTiffReader(tiffFile);

        grid = reader.read(null);
        RenderedImage image = grid.getRenderedImage();
        if (image != null) {
            gridData = image.getData();
        }
    }

    public void getDensity(double x, double y) throws InvalidGridGeometryException, TransformException {
        GridGeometry2D gg = grid.getGridGeometry();
        DirectPosition2D posWorld = new DirectPosition2D(x, y);
        GridCoordinates2D posGrid = gg.worldToGrid(posWorld);

        double[] pixel = new double[1];
        double[] data = gridData.getPixel(posGrid.x, posGrid.y, pixel);

        for (double d : data) {
            System.out.println(d);
        }
    }

Upvotes: 1

Related Questions