最近项目中需要解析发布的tif图的数据,我使用的是GeoTools进行解析,当然也可以使用 GDAL 等方式进行解析。直接贴代码吧就。
public static void main(String[] args) throws IOException, FactoryException {
long time=System.currentTimeMillis();
File file = new File("D:\\geoserver-2.19.0-bin\\data_dir\\data\\ImageMosaic\\nh3\\1_20230303.tif");
/**
* Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER:设置经度为第一轴顺序
*
*/
GeoTiffReader reader = new GeoTiffReader(file, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
GridCoverage2D coverage = reader.read(null);
//设置坐标系
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");
// 将 GridCoverage 进行重采样转换为另一个 CRS
coverage = (GridCoverage2D) Operations.DEFAULT.resample(coverage, targetCRS);
CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D();
// Envelope env = coverage.getEnvelope();
// RenderedImage image = coverage.getRenderedImage();
// 设置经纬度及坐标系等信息
DirectPosition position = new DirectPosition2D(crs, 29.67236, 113.54834);
// assume double
float[] f1 = (float[]) coverage.evaluate(position);
double[] doubleArray = new double[f1.length];
for (int i = 0; i < f1.length; i++) {
doubleArray[i] = (double) f1[i];
}
double[] sample = doubleArray;
// resample with the same array
sample = coverage.evaluate(position, sample);
System.out.println(sample);
}
这里是通过经纬度来获取指定点位的数据,可以参考 GeoTools官网