From 38ab580897dd25f84742a4c11d3033853f1513d6 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期六, 20 七月 2024 08:36:24 +0800 Subject: [PATCH] 1 --- SimuTools/Tools/Handle.cs | 373 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 371 insertions(+), 2 deletions(-) diff --git a/SimuTools/Tools/Handle.cs b/SimuTools/Tools/Handle.cs index f41d648..1ea8f07 100644 --- a/SimuTools/Tools/Handle.cs +++ b/SimuTools/Tools/Handle.cs @@ -4,6 +4,9 @@ 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; @@ -13,6 +16,10 @@ { 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> @@ -22,14 +29,21 @@ { 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); + //CopeWater(waterPath, outPath, layer); CopeFlow(flowPath, outPath, layer); CopeLayerJson(outPath, layer); + + if (Directory.Exists(temp)) Directory.Delete(temp, true); } + #region 鍦板舰 /// <summary> /// 澶勭悊鍦板舰 /// </summary> @@ -42,6 +56,7 @@ if (null == ds || 0 == ds.RasterCount || null == ds.GetSpatialRef()) return; SetTerrainInfo(ds, layer); + //CreateTerrainPng(ds, layer, outPath); } finally { @@ -58,28 +73,357 @@ Geometry maxPoint = GdalHelper.GetMaxPoint(ds); layer.extension = new Extension(minPoint.GetX(0), minPoint.GetY(0), maxPoint.GetX(0), maxPoint.GetY(0)); - Band band = ds.GetRasterBand(1); + 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]); + 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> + /// 鍒涘缓娴侀�熸祦鍚慞NG + /// </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> + /// 娴侀�熸祦鍚慣if鍊艰浆瀛樿嚦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閫氶亾琛ㄧず锛屾祦鍚戜负褰掍竴鍖栫殑浜岀淮鍚戦噺锛坸,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> @@ -95,5 +439,30 @@ sw.Write(json); } } + #endregion + + #region 鏆傛椂涓嶇敤 + /// <summary> + /// 閲嶉噰鏍� * + /// </summary> + private static void Resample(Dataset ds, string dest, int width, int height) + { + // 璁剧疆Warp鐨勯�夐」锛歨ttps://blog.csdn.net/qq_43210879/article/details/121350561 + string[] options = new string[] { + "format=GTiff", + "width=" + width, + "height=" + height, + "dstSRS=EPSG:4326" + }; + + OSGeo.GDAL.Driver driver = Gdal.GetDriverByName("GTiff"); + Dataset destDs = driver.Create(dest, width, height, ds.RasterCount, ds.GetRasterBand(1).DataType, null); + + GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options); + Gdal.Warp(destDs, new Dataset[] { ds }, warpAppOptions, null, null); + + destDs.Dispose(); + } + #endregion } } -- Gitblit v1.9.3