使用Java读取tif文件每个像素点值
1. 导入依赖
<dependency>
<groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-geotiff</artifactId>
<version>26.1.01</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>24.2</version>
</dependency>
<!-- 中央仓库没有 gt-geotiff, gt-shapefile 指定新的仓库 -->
<repositories>
<repository>
<id>GeoSolutions</id>
<url>http://maven.geo-solutions.it/</url>
</repository>
</repositories>
2. 相关代码
下面是一个测试的demo, 只要主要两个for中间的数据即可, 然后拿到数据进行统计等处理.
public class ReadPixel {
/**
* 根据栅格图层相关像素点信息
*
* @param path 栅格文件路径
* @throws Exception e
*/
private static void getPixelValue(String path) throws Exception {
GeoTiffReader geoTiffReader = new GeoTiffReader(path);
// 读取影像数据,获取2D覆盖层,可以理解为平面坐标系对象
GridCoverage2D coverage2D = geoTiffReader.read(null);
// 获取影像的渲染图像
RenderedImage renderedImage = coverage2D.getRenderedImage();
int width = renderedImage.getWidth();
int height = renderedImage.getHeight();
System.err.println("影像列数: " + width + ",影像行数: " + height);
// 获取影像的栅格数据
Raster raster = renderedImage.getData();
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// (x,y)点的值
double sampleDouble = raster.getSampleFloat(i, j, 0);
// 获取像素对应的经纬度信息
double[] lonLatByXAndY = getLonLatByXAndY(i, j, coverage2D);
System.out.println("经度: " + lonLatByXAndY[1] + ",纬度: " + lonLatByXAndY[0] + ",像素值: " + sampleDouble);
}
}
}
/**
* 根据横纵坐标获取经纬度,以及coverage2D获取取经纬度信息
* 注: 需要的话调用
*/
private static double[] getLonLatByXAndY(int i, int j, GridCoverage2D coverage2D) throws TransformException {
GridCoordinates2D gridCoordinate = new GridCoordinates2D(i, j);
DirectPosition2D realWorldCoordinate = (DirectPosition2D) coverage2D.getGridGeometry().gridToWorld(gridCoordinate);
double longitude = realWorldCoordinate.getX();
double latitude = realWorldCoordinate.getY();
return new double[]{latitude, longitude};
}
// 测试
public static void main(String[] args) throws Exception {
String path = "C:\\Users\\Administrator\\Desktop\\20240819_yield.tif";
getPixelValue(path);
}
}
具体的数据可以在getPixelValue
这个方法的双for中得到结果然后再根据自己的需求做统计