using ExportMap.db; using ExportMap.Models; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Web; namespace ExportMap.cs { public class XYZUtils { private static string pyFile; /// /// 获取Python文件 /// public static string PyFile { get { if (string.IsNullOrWhiteSpace(pyFile)) { pyFile = Path.Combine(ExportUtil.SourcesPath, "xyz.py"); } return pyFile; } } /// /// QGIS工程 /// public static string Qgz { get { //return Path.Combine(ExportUtil.SourcesPath, "xyz.qgz"); return "xyz.qgz"; } } /// /// 获取发布地址 /// public static string GetReleaseUrl(string dircode) { return "http://{host}/LFData/2d/tiles/" + dircode + "/{z}/{x}/{y}.png"; } /// /// 生成 /// /// XYZ参数 /// 错误信息 /// 数据发布ID public static int Generate(XYZArgs args, ref string err) { List list = selectMetas(args.ids, "and type in ('tif', 'tiff', 'img')"); if (null == list || list.Count == 0) return 0; string tifFile = Path.Combine(Tool.TempDir, ExportUtil.DateStr + ".txt"); string xyzPath = Path.Combine(SGUtils.LFData, "2d\\tiles", args.dircode); if (!Directory.Exists(xyzPath)) Directory.CreateDirectory(xyzPath); WriteText(tifFile, list); string cmd = string.Format("python \"{0}\" -qgz {1} -file \"{2}\" -out \"{3}\" -min {4} -max {5}", PyFile, Qgz, tifFile, xyzPath, args.min, args.max); //string pyText = File.ReadAllText(PyFile); //pyText = pyText // .Replace(@"E:\terrait\TianJin\ExportMap\ExportMap\Sources\xyz.qgz", Qgz) // .Replace(@"D:\xyz\zy.txt", tifFile) // .Replace(@"D:\xyz\tiles\zy", xyzPath) // .Replace("=12,", "=" + args.min + ",") // .Replace("=15,", "=" + args.max + ","); //string newPy = tifFile.Replace(".txt", ".py").Replace("\\", "\\\\"); //File.WriteAllText(newPy, pyText); //string cmd = string.Format("exec(open('{0}', 'r', encoding='utf-8').read()) & exit()", newPy); err = ExecCmd(cmd); if (File.Exists(tifFile)) File.Delete(tifFile); string viewFile = Path.Combine(xyzPath, "view.html"); if (File.Exists(viewFile)) { string path = "2d\\tiles" + "\\" + args.dircode; InsertToDB(list, args, path); return 1; } return 0; } /// /// 查询元数据 /// public static List selectMetas(List ids, string types = "") { string sql = string.Format("select * from lf.sys_meta where id in ({0}) {1} order by id", string.Join(",", ids), types); DataTable dt = Tool.DBHelper.GetDataTable(sql); List list = ModelHandler.FillModel(dt); return list; } /// /// 写文本文件 /// private static void WriteText(string file, List list) { string uploadFolder = Tool.GetSetting("uploadFolder"); List files = new List(); foreach (SysMeta meta in list) { string filePath = Path.Combine(uploadFolder, meta.path); if (File.Exists(filePath)) files.Add(filePath); } string str = string.Join("\n", files); File.WriteAllText(file, str); } /// /// 执行CMD /// /// 命令行 /// 执行结果或出错信息 public static String ExecCmd(string cmd) { string str = null; try { Process 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 so = p.StandardOutput; // 标准输出流 StreamReader se = p.StandardError; // 标准错误流 LogOut.Info("cmd = " + cmd); si.AutoFlush = true; si.WriteLine("cd \"C:\\Program Files\\QGIS 3.16\\apps\\Python37\""); si.WriteLine("\"C:\\Program Files\\QGIS 3.16\\bin\\qgis_process-qgis-ltr.bat\""); //si.WriteLine("\"C:\\Program Files\\QGIS 3.16\\bin\\python-qgis-ltr.bat\""); //si.WriteLine("exit()"); si.WriteLine(cmd); si.WriteLine("exit"); string info = so.ReadToEnd(); str = se.ReadToEnd(); if (!string.IsNullOrEmpty(info)) LogOut.Debug(info); if (!string.IsNullOrEmpty(str)) LogOut.Error(str); if (p.HasExited == false) p.Kill(); se.Close(); so.Close(); si.Close(); p.Close(); } catch (Exception ex) { LogOut.Error(ex.StackTrace); str = ex.Message; } return str; } /// /// 插入数据库 /// private static void InsertToDB(List metas, XYZArgs args, string path) { if (PubDBHelper.IsPublish(args.dircode)) return; SysPublish sys = NewPublish(metas[0], args); sys.path = path; int pubid = PubDBHelper.InsertPublish(sys); if (pubid > 0) { PubDBHelper.InsertLayer(sys, new SysMeta() { name = args.name, type = metas[0].type }); foreach (SysMeta meta in metas) { PubDBHelper.InsertMetaPub(meta.id, pubid, args.userId); } } } /// /// 创建数据发布类 /// private static SysPublish NewPublish(SysMeta meta, XYZArgs args) { SysPublish sp = new SysPublish(); sp.name = args.name; sp.url = GetReleaseUrl(args.dircode); sp.type = "DOM"; sp.status = 3; sp.dirid = args.dircode; sp.depid = args.depcode; sp.min = args.min; sp.max = args.max; sp.json = null; sp.create_user = args.userId; sp.geom = GetPointZ(args); sp.bak = null; return sp; } /// /// 获取中心点 /// private static string GetPointZ(XYZArgs args) { string viewFile = Path.Combine(SGUtils.LFData, "2d\\tiles", args.dircode, "view.html"); if (!File.Exists(viewFile)) return null; string str = File.ReadAllText(viewFile); int start = str.IndexOf(".setView([") + ".setView([".Length; int end = str.IndexOf(");", start); string coords = str.Substring(start, end - start).Replace("]", "").Replace(" ", ""); string[] strs = coords.Split(new char[] { ',' }); return string.Format("ST_GeomFromText('POINT Z ({0} {1} {2})')", strs[0], strs[1], strs[2]); } } }