java调用gdal 实现dem转矢量并将海拔值存入矢量文件属性 gdal版本为3.5.0
时间: 2024-05-08 16:15:42 浏览: 127
GDAL java版本
4星 · 用户满意度95%
以下是一个示例代码,用于将dem转换为矢量,并将海拔值存储在矢量文件的属性中。
```java
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Driver;
import org.gdal.ogr.Feature;
import org.gdal.ogr.FieldDefn;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
public class DEMtoVector {
public static void main(String[] args) {
// 加载GDAL库
gdal.AllRegister();
// 打开DEM数据集
String demFilePath = "path/to/dem.tif";
Dataset demDataset = gdal.Open(demFilePath, gdalconstConstants.GA_ReadOnly);
// 获取DEM数据集的投影信息
String projection = demDataset.GetProjectionRef();
// 创建矢量数据集
String vectorFilePath = "path/to/vector.shp";
Driver vectorDriver = ogr.GetDriverByName("ESRI Shapefile");
DataSource vectorDataSource = vectorDriver.CreateDataSource(vectorFilePath);
// 创建矢量图层
String vectorLayerName = "elevation";
Layer vectorLayer = vectorDataSource.CreateLayer(vectorLayerName, null, ogr.wkbPoint);
// 添加海拔值属性
FieldDefn elevationField = new FieldDefn("elevation", ogr.OFTReal);
vectorLayer.CreateField(elevationField);
// 将DEM数据集转换为矢量
int width = demDataset.getRasterXSize();
int height = demDataset.getRasterYSize();
double[] geotransform = demDataset.GetGeoTransform();
double xOrigin = geotransform[0];
double yOrigin = geotransform[3];
double pixelWidth = geotransform[1];
double pixelHeight = geotransform[5];
double[] elevationData = new double[1];
Geometry point = ogr.CreateGeometry(ogr.wkbPoint);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
double x = xOrigin + (col + 0.5) * pixelWidth;
double y = yOrigin + (row + 0.5) * pixelHeight;
demDataset.GetRasterBand(1).RasterIO(gdalconstConstants.GF_Read, col, row, 1, 1, elevationData, 1, 1, gdalconstConstants.GDT_Float64, 0, 0);
point.SetPoint_2D(0, x, y);
Feature feature = new Feature(vectorLayer.GetLayerDefn());
feature.SetGeometry(point);
feature.SetFieldDouble("elevation", elevationData[0]);
vectorLayer.CreateFeature(feature);
feature.delete();
}
}
// 释放资源
vectorDataSource.delete();
demDataset.delete();
ogr.RegisterAll();
}
}
```
注:以上代码仅供参考,具体实现方式可能因数据集格式、数据结构等因素而有所不同。
阅读全文