管道基础大数据平台系统开发-【CS】-ExportMap
34
13693261870
2024-07-20 c1ac20e223474eef374094107704f037f7218a19
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
using Newtonsoft.Json;
using OSGeo.GDAL;
using OSGeo.OGR;
using SimuTools.Domain;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SimuTools.Tools
{
    public class Handle
    {
        public static readonly int MAX = 256 * 256;
 
        public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"];
 
        public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory;
 
        /// <summary>
        /// 运行
        /// </summary>
        public static void Run(string terrainFile, string waterPath, string flowPath, string outPath)
        {
            Domain.Layer layer = new Domain.Layer();
            layer.duration = new Duration();
            layer.terrain = new Terrain();
            layer.waters = new Water();
 
            string temp = Path.Combine(outPath, "temp");
            if (!Directory.Exists(temp)) Directory.CreateDirectory(temp);
 
            CopeTerrain(terrainFile, outPath, layer);
            //CopeWater(waterPath, outPath, layer);
            CopeFlow(flowPath, outPath, layer);
            CopeLayerJson(outPath, layer);
 
            if (Directory.Exists(temp)) Directory.Delete(temp, true);
        }
 
        #region 地形
        /// <summary>
        /// 处理地形
        /// </summary>
        private static void CopeTerrain(string terrainFile, string outPath, Domain.Layer layer)
        {
            Dataset ds = null;
            try
            {
                ds = Gdal.Open(terrainFile, Access.GA_ReadOnly);
                if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
 
                SetTerrainInfo(ds, layer);
                //CreateTerrainPng(ds, layer, outPath);
            }
            finally
            {
                if (null != ds) ds.Dispose();
            }
        }
 
        /// <summary>
        /// 设置地形信息
        /// </summary>
        private static void SetTerrainInfo(Dataset ds, Domain.Layer layer)
        {
            Geometry minPoint = GdalHelper.GetMinPoint(ds);
            Geometry maxPoint = GdalHelper.GetMaxPoint(ds);
            layer.extension = new Extension(minPoint.GetX(0), minPoint.GetY(0), maxPoint.GetX(0), maxPoint.GetY(0));
 
            OSGeo.GDAL.Band band = ds.GetRasterBand(1);
            double[] mm = new double[2];
            band.ComputeRasterMinMax(mm, 0);
            layer.extension.SetHeight(mm[0], mm[1]);
        }
 
        /// <summary>
        /// 创建地形PNG
        /// </summary>
        private static void CreateTerrainPng(Dataset ds, Domain.Layer layer, string outPath)
        {
            string tempPath = Path.Combine(outPath, "temp");
            if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
            string terrainPath = Path.Combine(outPath, "terrain");
            if (!Directory.Exists(terrainPath)) Directory.CreateDirectory(terrainPath);
 
            foreach (int[] sizes in layer.terrain.size)
            {
                string tif = Path.Combine(tempPath, DateTime.Now.Ticks.ToString() + ".tif");
                Resample(ds.GetDescription(), tif, sizes[0], sizes[1]);
                //Resample(ds, tif, sizes[0], sizes[1]);
                if (!File.Exists(tif))
                {
                    continue;
                }
 
                string png = Path.Combine(terrainPath, sizes[0] + "_" + sizes[1] + ".png");
                Tif2Png(layer, tif, png, sizes[0], sizes[1]);
            }
        }
 
        /// <summary>
        /// 重采样
        /// </summary>
        private static void Resample(string source, string dest, int width, int height)
        {
            // https://blog.51cto.com/u_16099346/6691820
            string cmd = string.Format("{0}gdalwarp.exe -t_srs {1} -ts {2} {3} -r {4} -of GTiff \"{5}\" \"{6}\"", GdalPath, "EPSG:4326", width, height, "bilinear", source, dest);
            string err = ExecExe(cmd);
        }
 
        /// <summary>
        /// 执行命令
        /// </summary>
        public static string ExecExe(string cmd)
        {
            string str = null;
            Process p = null;
            try
            {
                p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.Start();
 
                StreamWriter si = p.StandardInput;
                StreamReader se = p.StandardError;
 
                si.AutoFlush = true;
                si.WriteLine(cmd);
                si.WriteLine("exit");
 
                str = se.ReadToEnd();
                se.Close();
                si.Close();
            }
            catch (Exception ex)
            {
                LogOut.Error(ex.Message + "\r\n" + ex.StackTrace);
                str = ex.Message;
            }
            finally
            {
                if (p != null) p.Close();
            }
            return str;
        }
 
        /// <summary>
        /// Tif值转存至Png
        /// </summary>
        private static void Tif2Png(Domain.Layer layer, string tif, string png, int width, int height)
        {
            Dataset ds = null;
            try
            {
                ds = Gdal.Open(tif, Access.GA_ReadOnly);
                if (null == ds || 0 == ds.RasterCount) return;
 
                OSGeo.GDAL.Band band = ds.GetRasterBand(1);
                float[] buffer = new float[width * height];
                band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);
 
                Bitmap image = new Bitmap(width, height);
                Graphics graphic = Graphics.FromImage(image);
                graphic.Clear(Color.Transparent); // 填充透明色
 
                //double perHeight = (layer.extension.maxHeight - layer.extension.minHeight) * 100 / 65536;
                //int val = Convert.ToInt32(buffer[x * y]* 100); //Convert.ToInt32((buffer[x * y] - layer.extension.minHeight) * 100);
                //int val = Convert.ToInt32((buffer[x * y] - layer.extension.minHeight) * 100 / perHeight);
 
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        int offset = x + y * width;
                        if (float.IsNaN(buffer[offset]) || buffer[offset] < -999)
                        {
                            //image.SetPixel(x, y, Color.Transparent);
                            continue;
                        }
 
                        int val = Convert.ToInt32(buffer[offset] * 100);
                        int r = val / 65536;
                        int g = (val - r * 65536) / 256;
                        int b = val % 256;
 
                        Color color = Color.FromArgb(127, r, g, b);
                        image.SetPixel(x, y, color);
                    }
                }
 
                image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
            }
            finally
            {
                if (null != ds) ds.Dispose();
                if (File.Exists(tif)) File.Delete(tif);
            }
        }
        #endregion
 
        #region 水面
        /// <summary>
        /// 处理水面
        /// </summary>
        private static void CopeWater(string waterPath, string outPath, Domain.Layer layer)
        {
            List<string> files = GetFiles(waterPath);
            if (null == files || files.Count == 0) return;
 
            SetWaterData(layer, files);
            if (files.Count != layer.waters.data.Count) return;
 
            /*for (int i = 0, c = files.Count; i < c; i++)
            {
                Dataset ds = null;
                try
                {
                    ds = Gdal.Open(files[i], Access.GA_ReadOnly);
                    if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) continue;
 
                    CreateWaterPng(ds, layer, outPath, layer.waters.data[i]);
                }
                finally
                {
                    if (null != ds) ds.Dispose();
                }
            }*/
            Parallel.For(0, files.Count, i =>
            {
                Dataset ds = null;
                try
                {
                    ds = Gdal.Open(files[i], Access.GA_ReadOnly);
                    if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return;
 
                    CreateWaterPng(ds, layer, outPath, layer.waters.data[i]);
                }
                finally
                {
                    if (null != ds) ds.Dispose();
                }
            });
        }
 
        /// <summary>
        /// 创建水面PNG
        /// </summary>
        private static void CreateWaterPng(Dataset ds, Domain.Layer layer, string outPath, long ticks)
        {
            string tempPath = Path.Combine(outPath, "temp");
            if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
            string waterPath = Path.Combine(outPath, "waters", ticks.ToString());
            if (!Directory.Exists(waterPath)) Directory.CreateDirectory(waterPath);
 
            foreach (int[] sizes in layer.terrain.size)
            {
                string fileName = Path.GetFileNameWithoutExtension(ds.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
                string tif = Path.Combine(tempPath, fileName + ".tif");
                Resample(ds.GetDescription(), tif, sizes[0], sizes[1]);
                if (!File.Exists(tif))
                {
                    continue;
                }
 
                string png = Path.Combine(waterPath, sizes[0] + "_" + sizes[1] + ".png");
                Tif2Png(layer, tif, png, sizes[0], sizes[1]);
            }
        }
 
        /// <summary>
        /// 获取文件
        /// </summary>
        private static List<String> GetFiles(string path, string prefix = "")
        {
            string[] files = Directory.GetFiles(path, prefix + "*.tif?", SearchOption.TopDirectoryOnly);
            if (null == files || files.Length == 0) return null;
 
            List<string> list = files.ToList();
            list.Sort();
 
            return list;
        }
 
        /// <summary>
        /// 设置水面数据
        /// </summary>
        private static void SetWaterData(Domain.Layer layer, List<string> files)
        {
            DateTime now = DateTime.Now;
            long startTicks = new DateTime(1970, 1, 1, 8, 0, 0).Ticks;
 
            foreach (string file in files)
            {
                string fileName = Path.GetFileNameWithoutExtension(file);
                int hour = Convert.ToInt32(fileName.Substring(0, 2));
                int minute = Convert.ToInt32(fileName.Substring(2, 2));
                int second = Convert.ToInt32(fileName.Substring(4, 2));
 
                DateTime d = new DateTime(now.Year, now.Month, now.Day, hour, minute, second);
                layer.waters.data.Add((d.Ticks - startTicks) / 10000);
            }
        }
        #endregion
 
        #region 流速流向
        /// <summary>
        /// 处理流速流向
        /// </summary>
        private static void CopeFlow(string flowPath, string outPath, Domain.Layer layer)
        {
            List<string> vxFiles = GetFiles(flowPath, "vx");
            List<string> vyFiles = GetFiles(flowPath, "vy");
            if (null == vxFiles || null == vyFiles || vxFiles.Count != vyFiles.Count || vxFiles.Count != layer.waters.data.Count) return;
 
            Parallel.For(0, vxFiles.Count, i =>
            {
                Dataset vxDs = null, vyDs = null;
                try
                {
                    vxDs = Gdal.Open(vxFiles[i], Access.GA_ReadOnly);
                    if (null == vxDs || 0 == vxDs.RasterCount || null == vxDs.GetSpatialRef() ||
                        null == vyDs || 0 == vyDs.RasterCount || null == vyDs.GetSpatialRef()) return;
 
                    CreateFlowPng(vxDs, vyDs, layer, outPath, layer.waters.data[i]);
                }
                finally
                {
                    if (null != vxDs) vxDs.Dispose();
                    if (null != vyDs) vyDs.Dispose();
                }
            });
        }
 
        /// <summary>
        /// 创建流速流向PNG
        /// </summary>
        private static void CreateFlowPng(Dataset vxDs, Dataset vyDs, Domain.Layer layer, string outPath, long ticks)
        {
            string tempPath = Path.Combine(outPath, "temp");
            if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
            string flowPath = Path.Combine(outPath, "flows", ticks.ToString());
            if (!Directory.Exists(flowPath)) Directory.CreateDirectory(flowPath);
 
            foreach (int[] sizes in layer.terrain.size)
            {
                string vxName = Path.GetFileNameWithoutExtension(vxDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
                string vxTif = Path.Combine(tempPath, vxName + ".tif");
                Resample(vxDs.GetDescription(), vxTif, sizes[0], sizes[1]);
 
                string vyName = Path.GetFileNameWithoutExtension(vyDs.GetDescription()) + "_" + sizes[0] + "_" + sizes[1];
                string vyTif = Path.Combine(tempPath, vyName + ".tif");
                Resample(vyDs.GetDescription(), vyTif, sizes[0], sizes[1]);
 
                if (!File.Exists(vxTif) || !File.Exists(vyTif)) continue;
 
                string png = Path.Combine(flowPath, sizes[0] + "_" + sizes[1] + ".png");
                VxyTif2Png(layer, vxTif, vyTif, png, sizes[0], sizes[1]);
            }
        }
 
        /// <summary>
        /// 流速流向Tif值转存至Png
        /// </summary>
        private static void VxyTif2Png(Domain.Layer layer, string vxTif, string vyTif, string png, int width, int height)
        {
            Dataset vxDs = null, vyDs = null;
            try
            {
                vxDs = Gdal.Open(vxTif, Access.GA_ReadOnly);
                vyDs = Gdal.Open(vyTif, Access.GA_ReadOnly);
                if (null == vxDs || 0 == vxDs.RasterCount || null == vyDs || 0 == vyDs.RasterCount) return;
 
                float[] vxBuffer = new float[width * height], vyBuffer = new float[width * height];
                vxDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vxBuffer, width, height, 0, 0);
                vyDs.GetRasterBand(1).ReadRaster(0, 0, width, height, vyBuffer, width, height, 0, 0);
 
                Bitmap image = new Bitmap(width, height);
                Graphics graphic = Graphics.FromImage(image);
                graphic.Clear(Color.Transparent); // 填充透明色
 
                // 用 R通道表示,流向为归一化的二维向量(x,y),G通道表示为 x *255 , B通道表示为 y * 255
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        int offset = x + y * width;
                        if (float.IsNaN(vxBuffer[offset]) || vxBuffer[offset] < -999 ||
                            float.IsNaN(vyBuffer[offset]) || vyBuffer[offset] < -999) continue;
 
                        float vx = vxBuffer[offset], vy = vyBuffer[offset];
                        //int val = Convert.ToInt32(vxBuffer[offset] * 100);
                        //int r = val / 65536;
                        //int g = (val - r * 65536) / 256;
                        //int b = val % 256;
                        int r = 0;
                        int g = 0;
                        int b = 0;
 
                        Color color = Color.FromArgb(127, r, g, b);
                        image.SetPixel(x, y, color);
                    }
                }
 
                image.Save(png, System.Drawing.Imaging.ImageFormat.Png);
            }
            finally
            {
                if (null != vxDs) vxDs.Dispose();
                if (null != vyDs) vyDs.Dispose();
                if (File.Exists(vxTif)) File.Delete(vxTif);
                if (File.Exists(vyTif)) File.Delete(vyTif);
            }
        }
        #endregion
 
        #region 元数据
        /// <summary>
        /// 处理元数据
        /// </summary>
        private static void CopeLayerJson(string outPath, Domain.Layer layer)
        {
            if (null == layer) return;
 
            String json = JsonConvert.SerializeObject(layer);
 
            string filePath = Path.Combine(outPath, "layer.json");
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                sw.Write(json);
            }
        }
        #endregion
 
        #region 暂时不用
        /// <summary>
        /// 重采样 *
        /// </summary>
        private static void Resample(Dataset ds, string dest, int width, int height)
        {
            // https://blog.51cto.com/u_16099346/6691820
            //string args = string.Format("-t_srs {0} -ts {1} {2} -r {3} -of {4}", "EPSG:4326", width, height, "bilinear", "GTiff");
            //string[] options = Gdal.ParseCommandLine(args);
 
            string[] options = new string[]
            {
                "-t_srs",
                "EPSG:4326",
                "-ts",
                width.ToString(),
                height.ToString(),
                "-r",
                "bilinear",
                "-of",
                "GTiff"
            };
            GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options);
 
            Dataset destDs = Gdal.Warp(dest, new Dataset[] { ds }, warpAppOptions, null, null);
            destDs.Dispose();
        }
        #endregion
    }
}