1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
/**
* 从文件读取数据
*
* @param info
* @param file
* @return {@link float[][] }
*/
public static float[][] readDataFromFile(Info info, File file) throws FileNotFoundException {
float[][] data = new float[info.getRows()][info.getCols()];
try (Scanner scanner = new Scanner(file)) {
// 跳过文件头
for (int i = 0; i < 6; i++) {
scanner.nextLine();
}
int col = 0;
int row = 0;
AtomicInteger count = new AtomicInteger(0);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.trim().isEmpty()) {
continue;
}
count.incrementAndGet();
try (Scanner lineScanner = new Scanner(line)) {
while (lineScanner.hasNext()) {
float height = lineScanner.nextFloat();
data[col][row] = height;
col++;
}
}
col = 0;
row++;
}
}
return data;
}
/**
* 另存为tiff
*
* @param outInfo out信息
* @param data 数据
* @throws IOException IOException
*/
public static void saveAsTiff(OutInfo outInfo, float[][] data, File targetTiff) throws IOException {
double width = outInfo.getCols() * outInfo.getCellSize();
double height = outInfo.getRows() * outInfo.getCellSize();
double xMin = outInfo.getX() - width / 2.0;
double yMin = outInfo.getY() - height / 2.0;
Envelope referencedEnvelope = new Envelope2D(DefaultGeographicCRS.WGS84, xMin, yMin, width, height);
GridCoverageFactory factory = new GridCoverageFactory();
GridCoverage2D outputCoverage = factory.create("GridCoverage", data, referencedEnvelope);
GeoTiffWriter writer = null;
try {
writer = new GeoTiffWriter(targetTiff);
GeoTiffFormat geoTiffFormat = new GeoTiffFormat();
ParameterValueGroup writeParameters = geoTiffFormat.getWriteParameters();
List<GeneralParameterValue> valueList = writeParameters.values();
writer.write(outputCoverage, valueList.toArray(new GeneralParameterValue[0]));
} finally {
if (writer!=null){
writer.dispose();
}
}
}
public static void main(String[] args) throws Exception {
String out = "F:/Data/raster/data.txt";
File file = new File(out);
Info info = new Info(file);
float[][] data = OutUtil.readDataFromFile(info, file);
String targetTiff = "F:/Data/raster/data.tiff";
OutUtil.saveAsTiff(info, data, new File(targetTiff));
}
|
Preview: