气象天气数据为nc文件,工作需要栅格tif,因此需要将nc文件转为tif。使用springboot实现功能
1、导入pom依赖
<dependency>
<groupId>org.gdal</groupId>
<artifactId>gdal</artifactId>
<version>3.5.0</version>
</dependency>
<!-- netcdf4 -->
<dependency>
<groupId>edu.ucar</groupId>
<artifactId>netcdf4</artifactId>
<version>4.5.5</version>
</dependency>
2、编写nc转tif的方法
public static void ncToTif(String ncPath, String tiffName, String varName) {
NetcdfFile openNC = null; //filePath:文件地址
try {
openNC = NetcdfFile.open(ncPath);
Variable lon = openNC.findVariable("longitude");
Variable lat = openNC.findVariable("latitude");
Variable aod = openNC.findVariable(varName);
float[] lonList = (float[]) lon.read().copyToNDJavaArray();
float[] latList = (float[]) lat.read().copyToNDJavaArray();
float[][] aodList = (float[][]) aod.read().copyToNDJavaArray();
int cols = lonList.length;
int rows = latList.length;
double[] data = new double[cols * rows];
for (int i = 0, len = aodList.length; i < len; i++) {
float[] _pre = aodList[i];
int curRow = rows - i - 1;
for (int j = 0, jlen = _pre.length; j < jlen; j++) {
data[curRow * cols + j] = Double.parseDouble(String.valueOf(_pre[j]));
}
}
float lonMax = ArrayUtil.max(lonList);
float lonMin = ArrayUtil.min(lonList);
float latMax = ArrayUtil.max(latList);
float latMin = ArrayUtil.min(latList);
int latLength = latList.length;
int lonLength = lonList.length;
float Lon_Res = (lonMax - lonMin) / (lonLength - 1);
float Lat_Res = (latMax - latMin) / (latLength - 1);
Driver driver = gdal.GetDriverByName(gdal_driver_tif);
Dataset dataset = driver.Create(tiffName, lonLength, latLength, 1, 6);
double[] geotransform = {lonMin, Lon_Res, 0F, latMax, 0F, -Lat_Res};
dataset.SetGeoTransform(geotransform);
Band out_band = dataset.GetRasterBand(1);
out_band.WriteRaster(0, 0, lonLength, latLength, data);
SpatialReference spatialReference = new SpatialReference();
spatialReference.SetWellKnownGeogCS("WGS84");
dataset.SetProjection(spatialReference.ExportToWkt());
dataset.FlushCache();
openNC.close();
dataset.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
3、测试
public static void main(String[] args) {
String ncPath="D://xxx.nc"
String tifPath="D://xxx.shp"
String var = "tianqi";
ncToTif(ncPath,tifPath,var );
}