public static void TransposeShp(string[] args) { var srcImage = ShpReader.Load(args[1]); var srcFrames = srcImage.Frames.ToArray(); var destFrames = srcImage.Frames.ToArray(); for (var z = 3; z < args.Length - 2; z += 3) { var start = Exts.ParseIntegerInvariant(args[z]); var m = Exts.ParseIntegerInvariant(args[z + 1]); var n = Exts.ParseIntegerInvariant(args[z + 2]); for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { destFrames[start + i * n + j] = srcFrames[start + j * m + i]; } } } using (var destStream = File.Create(args[2])) ShpReader.Write(destStream, srcImage.Size, destFrames.Select(f => f.Data)); }
private void VectorCoordTransform(string physicsFilePath, string OutCoordFile, string newFile) { try { GdalHelp.InitGdal(); ShpReader sr = new ShpReader(physicsFilePath); string csSrc = sr.GetSridWkt(); string csDest = File.ReadAllText(OutCoordFile); iTelluro.DataTools.Utility.GIS.CoordTransform.Ogrtransform(csSrc, csDest, physicsFilePath, newFile); if (File.Exists(newFile)) { Info(UtilityMessageConvert.Get("转换成功")); } else { Error(UtilityMessageConvert.Get("转换失败")); } } catch (Exception ex) { Abp.Logging.LogHelper.LogException(ex); throw; } }
public static void TransposeShp(string[] args) { var srcImage = ShpReader.Load(args[1]); var srcFrames = srcImage.Frames.ToArray(); var destFrames = srcImage.Frames.ToArray(); for (var z = 3; z < args.Length - 2; z += 3) { var start = int.Parse(args[z]); var m = int.Parse(args[z + 1]); var n = int.Parse(args[z + 2]); for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { destFrames[start + i * n + j] = srcFrames[start + j * m + i]; } } } using (var destStream = File.Create(args[2])) ShpWriter.Write(destStream, srcImage.Width, srcImage.Height, destFrames.Select(f => f.Image)); }
public static ResourceTemplate RenderResourceType(ResourceTypeInfo info, string[] exts, Palette p) { var image = info.SpriteNames[0]; using (var s = FileSystem.OpenWithExts(image, exts)) { var shp = new ShpReader(s); var frame = shp[shp.ImageCount - 1]; var bitmap = new Bitmap(shp.Width, shp.Height, PixelFormat.Format8bppIndexed); bitmap.Palette = p.AsSystemPalette(); var data = bitmap.LockBits(bitmap.Bounds(), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); unsafe { byte *q = (byte *)data.Scan0.ToPointer(); var stride = data.Stride; for (var i = 0; i < shp.Width; i++) { for (var j = 0; j < shp.Height; j++) { q[j * stride + i] = frame.Image[i + shp.Width * j]; } } } bitmap.UnlockBits(data); return(new ResourceTemplate { Bitmap = bitmap, Info = info, Value = shp.ImageCount - 1 }); } }
private void BuildGrid() { WebMercatorGrid grid = new WebMercatorGrid(); // List <Coordinate> coordinates = new List <Coordinate>(); coordinates.Add(new Coordinate(109, 20)); coordinates.Add(new Coordinate(117.2, 25.6)); Bound bound = new Bound(coordinates); //构建尺度6格网 for (int i = 10; i < 17; i++) { grid.Build(bound, i); } //shpfile路径 string shpPath = System.IO.Directory.GetCurrentDirectory() + @"\DATA\shp\china\guangdong.shp"; ShpReader shpReader = new ShpReader(); shpReader.Read(shpPath); // string outputDir = System.IO.Directory.GetCurrentDirectory() + @"\dataset"; grid.CutShape(shpReader.FeaureCollection, outputDir); }
public static ActorTemplate RenderActor(ActorInfo info, TileSet tileset, Palette p) { var image = RenderSprites.GetImage(info); using (var s = FileSystem.OpenWithExts(image, tileset.Extensions)) { var shp = new ShpReader(s); var bitmap = RenderShp(shp, p); try { using (var s2 = FileSystem.OpenWithExts(image + "2", tileset.Extensions)) { var shp2 = new ShpReader(s2); var roofBitmap = RenderShp(shp2, p); using (var g = System.Drawing.Graphics.FromImage(bitmap)) g.DrawImage(roofBitmap, 0, 0); } } catch { } return(new ActorTemplate { Bitmap = bitmap, Info = info, Appearance = info.Traits.GetOrDefault <EditorAppearanceInfo>() }); } }
public static void ConvertShpToPng(string[] args) { var src = args[1]; var dest = Path.ChangeExtension(src, ".png"); var srcImage = ShpReader.Load(src); var shouldRemap = args.Contains("--transparent"); var palette = Palette.Load(args[2], shouldRemap); using (var bitmap = new Bitmap(srcImage.ImageCount * srcImage.Width, srcImage.Height, PixelFormat.Format8bppIndexed)) { var x = 0; bitmap.Palette = palette.AsSystemPalette(); foreach (var frame in srcImage.Frames) { var data = bitmap.LockBits(new Rectangle(x, 0, srcImage.Width, srcImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); for (var i = 0; i < bitmap.Height; i++) { Marshal.Copy(frame.Image, i * srcImage.Width, new IntPtr(data.Scan0.ToInt64() + i * data.Stride), srcImage.Width); } x += srcImage.Width; bitmap.UnlockBits(data); } bitmap.Save(dest); } }
/// <summary> /// 计算线的交点 /// 先获取每条线段的startpoint与endpoint,然后判断是否有重合 /// </summary> private List <Point3d> CalPoints(string path, RasterReader reader) { ShpReader shp = new ShpReader(path); OSGeo.OGR.Feature ofea; List <Point3d> linePoint = new List <Point3d>(); List <OSGeo.OGR.Geometry> featureList = new List <OSGeo.OGR.Geometry>(); while (((ofea = shp.layer.GetNextFeature()) != null)) { int count = ofea.GetGeometryRef().GetPointCount(); Point3d start = new Point3d(ofea.GetGeometryRef().GetX(0), ofea.GetGeometryRef().GetY(0), GetElevationByPointInDEM(new Point2d(ofea.GetGeometryRef().GetX(0), ofea.GetGeometryRef().GetY(0)), reader)); Point3d end = new Point3d(ofea.GetGeometryRef().GetX(count - 1), ofea.GetGeometryRef().GetY(count - 1), GetElevationByPointInDEM(new Point2d(ofea.GetGeometryRef().GetX(0), ofea.GetGeometryRef().GetY(0)), reader)); if (!linePoint.Contains(start)) { linePoint.Add(start); } if (!linePoint.Contains(end)) { linePoint.Add(end); } featureList.Add(ofea.GetGeometryRef()); } return(linePoint.OrderBy(t => t.Y).ToList()); }
/// <summary> /// 获取河流的主点 /// </summary> /// <param name="mainShp"></param> /// <param name="featureList"></param> /// <returns></returns> private List <Point2d> GetRiverPoints(string mainShp, out List <OSGeo.OGR.Geometry> featureList) { ShpReader shp = new ShpReader(mainShp); OSGeo.OGR.Feature ofea; List <Point2d> linePoint = new List <Point2d>(); featureList = new List <OSGeo.OGR.Geometry>(); while (((ofea = shp.layer.GetNextFeature()) != null)) { int count = ofea.GetGeometryRef().GetPointCount(); Point2d start = new Point2d(ofea.GetGeometryRef().GetX(0), ofea.GetGeometryRef().GetY(0)); Point2d end = new Point2d(ofea.GetGeometryRef().GetX(count - 1), ofea.GetGeometryRef().GetY(count - 1)); if (!linePoint.Contains(start)) { linePoint.Add(start); } if (!linePoint.Contains(end)) { linePoint.Add(end); } featureList.Add(ofea.GetGeometryRef()); } return(linePoint.OrderBy(t => t.Y).ToList()); }
static Bitmap RenderShp(ShpReader shp, Palette p) { var frame = shp[0]; var bitmap = new Bitmap(shp.Width, shp.Height, PixelFormat.Format8bppIndexed); bitmap.Palette = p.AsSystemPalette(); var data = bitmap.LockBits(bitmap.Bounds(), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); unsafe { byte *q = (byte *)data.Scan0.ToPointer(); var stride2 = data.Stride; for (var i = 0; i < shp.Width; i++) { for (var j = 0; j < shp.Height; j++) { q[j * stride2 + i] = frame.Image[i + shp.Width * j]; } } } bitmap.UnlockBits(data); return(bitmap); }
public static ResourceTemplate RenderResourceType(ResourceTypeInfo info, string[] exts, Palette p) { var image = info.EditorSprite; using (var s = FileSystem.OpenWithExts(image, exts)) { // TODO: Do this properly var shp = new ShpReader(s) as ISpriteSource; var frame = shp.Frames.Last(); var bitmap = new Bitmap(frame.Size.Width, frame.Size.Height, PixelFormat.Format8bppIndexed); bitmap.Palette = p.AsSystemPalette(); var data = bitmap.LockBits(bitmap.Bounds(), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); unsafe { byte *q = (byte *)data.Scan0.ToPointer(); var stride = data.Stride; for (var i = 0; i < frame.Size.Width; i++) { for (var j = 0; j < frame.Size.Height; j++) { q[j * stride + i] = frame.Data[i + frame.Size.Width * j]; } } } bitmap.UnlockBits(data); return(new ResourceTemplate { Bitmap = bitmap, Info = info, Value = shp.Frames.Count() - 1 }); } }
public static void RemapShp(string[] args) { var remap = new Dictionary <int, int>(); /* the first 4 entries are fixed */ for (var i = 0; i < 4; i++) { remap[i] = i; } var srcMod = args[1].Split(':')[0]; Game.modData = new ModData(srcMod); FileSystem.LoadFromManifest(Game.modData.Manifest); Rules.LoadRules(Game.modData.Manifest, new Map()); var srcPaletteInfo = Rules.Info["player"].Traits.Get <PlayerColorPaletteInfo>(); int[] srcRemapIndex = srcPaletteInfo.RemapIndex; var destMod = args[2].Split(':')[0]; Game.modData = new ModData(destMod); FileSystem.LoadFromManifest(Game.modData.Manifest); Rules.LoadRules(Game.modData.Manifest, new Map()); var destPaletteInfo = Rules.Info["player"].Traits.Get <PlayerColorPaletteInfo>(); int[] destRemapIndex = destPaletteInfo.RemapIndex; int[] ShadowIndex = { }; // the remap range is always 16 entries, but their location and order changes for (var i = 0; i < 16; i++) { remap[PlayerColorRemap.GetRemapIndex(srcRemapIndex, i)] = PlayerColorRemap.GetRemapIndex(destRemapIndex, i); } // map everything else to the best match based on channel-wise distance var srcPalette = Palette.Load(args[1].Split(':')[1], ShadowIndex); var destPalette = Palette.Load(args[2].Split(':')[1], ShadowIndex); var fullIndexRange = Exts.MakeArray <int>(256, x => x); for (var i = 0; i < 256; i++) { if (!remap.ContainsKey(i)) { remap[i] = fullIndexRange .Where(a => !remap.ContainsValue(a)) .OrderBy(a => ColorDistance(destPalette.Values[a], srcPalette.Values[i])) .First(); } } var srcImage = ShpReader.Load(args[3]); using (var destStream = File.Create(args[4])) ShpWriter.Write(destStream, srcImage.Width, srcImage.Height, srcImage.Frames.Select(im => im.Image.Select(px => (byte)remap[px]).ToArray())); }
public static void RemapShp(string[] args) { var remap = new Dictionary <int, int>(); /* the first 4 entries are fixed */ for (var i = 0; i < 4; i++) { remap[i] = i; } var srcMod = args[1].Split(':')[0]; Game.modData = new ModData(srcMod); GlobalFileSystem.LoadFromManifest(Game.modData.Manifest); var srcRules = Game.modData.RulesetCache.LoadDefaultRules(); var srcPaletteInfo = srcRules.Actors["player"].Traits.Get <PlayerColorPaletteInfo>(); var srcRemapIndex = srcPaletteInfo.RemapIndex; var destMod = args[2].Split(':')[0]; Game.modData = new ModData(destMod); GlobalFileSystem.LoadFromManifest(Game.modData.Manifest); var destRules = Game.modData.RulesetCache.LoadDefaultRules(); var destPaletteInfo = destRules.Actors["player"].Traits.Get <PlayerColorPaletteInfo>(); var destRemapIndex = destPaletteInfo.RemapIndex; var shadowIndex = new int[] { }; // the remap range is always 16 entries, but their location and order changes for (var i = 0; i < 16; i++) { remap[PlayerColorRemap.GetRemapIndex(srcRemapIndex, i)] = PlayerColorRemap.GetRemapIndex(destRemapIndex, i); } // map everything else to the best match based on channel-wise distance var srcPalette = new ImmutablePalette(args[1].Split(':')[1], shadowIndex); var destPalette = new ImmutablePalette(args[2].Split(':')[1], shadowIndex); for (var i = 0; i < Palette.Size; i++) { if (!remap.ContainsKey(i)) { remap[i] = Enumerable.Range(0, Palette.Size) .Where(a => !remap.ContainsValue(a)) .MinBy(a => ColorDistance(destPalette[a], srcPalette[i])); } } var srcImage = ShpReader.Load(args[3]); using (var destStream = File.Create(args[4])) ShpReader.Write(destStream, srcImage.Size, srcImage.Frames.Select(im => im.Data.Select(px => (byte)remap[px]).ToArray())); }
private List <Dictionary <Point2d, Geometry> > GetAllRivers(string mainShp) { //获取主沟道 ShpReader shp = new ShpReader(mainShp); List <OSGeo.OGR.Feature> maxFeature = new List <OSGeo.OGR.Feature>(); List <Geometry> geoList = null; List <Point2d> pts1 = GetRiverPoints(mainShp, out geoList); List <Dictionary <Point2d, Geometry> > dic = new List <Dictionary <Point2d, Geometry> >(); GetLineByPoint(pts1[0], geoList, ref dic); return(dic); }
public void Shp_Parse_States() { //Z:\geospatial\Geospatial\census_shp_files\cb_2018_us_state_5m\cb_2018_us_state_5m.shp string path = @"Z:\geospatial\Geospatial\census_shp_files\cb_2018_us_state_5m\cb_2018_us_state_5m.shp"; byte[] data = System.IO.File.ReadAllBytes(path); ShpReader reader = new ShpReader(); reader.Parse(data); Assert.NotNull(reader.OutPolygons); Assert.True(reader.OutPolygons.Count == 56); }
/// <summary> /// 导出主沟道 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { if (_mainRiver == null) { MsgBox.ShowInfo("暂时未计算主沟道"); return; } SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "矢量文件|*.shp"; if (dialog.ShowDialog() == DialogResult.OK) { ShpReader shp = new ShpReader(fileChooseControl3.FilePath); CreateShp(dialog.FileName, _mainRiver, shp.SpatialRef); System.Diagnostics.Process.Start("Explorer.exe", Path.GetDirectoryName(dialog.FileName)); } }
public static void ConvertPngToShp(string[] args) { var dest = args[1].Split('-').First() + ".shp"; var frames = args.Skip(1).Select(a => PngLoader.Load(a)); var size = frames.First().Size; if (frames.Any(f => f.Size != size)) { throw new InvalidOperationException("All frames must be the same size"); } using (var destStream = File.Create(dest)) ShpReader.Write(destStream, size, frames.Select(f => f.ToBytes())); Console.WriteLine(dest + " saved."); }
public static void RemapShp(string[] args) { var remap = new Dictionary <int, int>(); /* the first 4 entries are fixed */ for (var i = 0; i < 4; i++) { remap[i] = i; } var srcPaletteType = Enum <PaletteFormat> .Parse(args[1].Split(':')[0]); var destPaletteType = Enum <PaletteFormat> .Parse(args[2].Split(':')[0]); /* the remap range is always 16 entries, but their location and order changes */ for (var i = 0; i < 16; i++) { remap[PlayerColorRemap.GetRemapIndex(srcPaletteType, i)] = PlayerColorRemap.GetRemapIndex(destPaletteType, i); } /* map everything else to the best match based on channel-wise distance */ var srcPalette = Palette.Load(args[1].Split(':')[1], false); var destPalette = Palette.Load(args[2].Split(':')[1], false); var fullIndexRange = Exts.MakeArray <int>(256, x => x); for (var i = 0; i < 256; i++) { if (!remap.ContainsKey(i)) { remap[i] = fullIndexRange .Where(a => !remap.ContainsValue(a)) .OrderBy(a => ColorDistance(destPalette.Values[a], srcPalette.Values[i])) .First(); } } var srcImage = ShpReader.Load(args[3]); using (var destStream = File.Create(args[4])) ShpWriter.Write(destStream, srcImage.Width, srcImage.Height, srcImage.Frames.Select(im => im.Image.Select(px => (byte)remap[px]).ToArray())); }
public static void ConvertShpToPng(string[] args) { var src = args[1]; var dest = Path.ChangeExtension(src, ".png"); var srcImage = ShpReader.Load(src); var shadowIndex = new int[] { }; if (args.Contains("--noshadow")) { Array.Resize(ref shadowIndex, shadowIndex.Length + 3); shadowIndex[shadowIndex.Length - 1] = 1; shadowIndex[shadowIndex.Length - 2] = 3; shadowIndex[shadowIndex.Length - 3] = 4; } var palette = Palette.Load(args[2], shadowIndex); using (var bitmap = new Bitmap(srcImage.ImageCount * srcImage.Width, srcImage.Height, PixelFormat.Format8bppIndexed)) { var x = 0; bitmap.Palette = palette.AsSystemPalette(); foreach (var frame in srcImage.Frames) { var data = bitmap.LockBits(new Rectangle(x, 0, srcImage.Width, srcImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); for (var i = 0; i < bitmap.Height; i++) { Marshal.Copy(frame.Image, i * srcImage.Width, new IntPtr(data.Scan0.ToInt64() + i * data.Stride), srcImage.Width); } x += srcImage.Width; bitmap.UnlockBits(data); } bitmap.Save(dest); Console.WriteLine(dest + " saved"); } }
public List <string> GetCoordList(List <string> fileList) { List <string> ret = new List <string>(); foreach (string s in fileList) { ShpReader sr = new ShpReader(s); string wkt = sr.GetSridWkt(); if (!string.IsNullOrEmpty(wkt)) { SpatialReference srf = new SpatialReference(wkt); string strHTML = srf.__str__().Replace("\n", "<br/>").Replace("[\"", ":").Replace("]", ""); string Lyr = wkt.Substring(wkt.IndexOf("\"") + 1, wkt.IndexOf(",") - wkt.IndexOf("\"") - 2); ret.Add(s + "|" + Lyr + "|" + strHTML); } } return(ret); }
public void RasterTile_Counties() { string path = @"Z:\geospatial\Geospatial\census_shp_files\cb_2018_us_county_20m\cb_2018_us_county_20m.shp"; byte[] data = System.IO.File.ReadAllBytes(path); ShpReader reader = new ShpReader(); reader.Parse(data); List <Polygon> polys = reader.OutPolygons; RasterTileRenderer renderer = new RasterTileRenderer(); renderer.RenderPolygons(polys, 0, 0, 1); renderer.RenderPolygons(polys, 6, 13, 5); renderer.RenderPolygons(polys, 7, 13, 5); renderer.RenderPolygons(polys, 8, 13, 5); //renderer.RenderPolygons(polys, System.Drawing.Color.Blue, 0, 0, 1); }
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { double[] result = e.Result as double[]; if (Convert.ToDouble(result[0]) != 0) { textBox1.Text = result[0].ToString(); } if (Convert.ToDouble(result[1]) != 0) { textBox2.Text = result[1].ToString(); } if (Convert.ToDouble(result[2]) != 0) { textBox3.Text = result[2].ToString(); } FormOutput.AppendProress(false); //输出主沟道到临时目录并且加载到三维球和节点 string tempPath = Path.Combine(Path.GetTempPath(), "主沟道" + DateTime.Now.ToString("HH_mm") + ".shp"); ShpReader shp = new ShpReader(fileChooseControl3.FilePath); CreateShp(tempPath, _mainRiver, shp.SpatialRef); _parent.AddShpLineLayerByPath(tempPath); }
public static void Build() { _isRunning = true; //1.搜索线 IShpReader lineReader = new ShpReader(_dir + @"\" + _lineName + ".shp"); WebMercatorGrid lineGrid = new WebMercatorGrid(); for (int i = _startLevel; i < _endLevel; i++) { lineGrid.Build(lineReader.Bounds, i); } //1.1线切片输出 lineGrid.CutShapeOrderByGrid(lineReader, _outDir + _lineName + @"\"); //2.搜索面 IShpReader polygonReader = new ShpReader(_dir + @"\" + _polygonName + ".shp"); WebMercatorGrid polygonGrid = new WebMercatorGrid(); for (int i = _startLevel; i < _endLevel; i++) { polygonGrid.Build(polygonReader.Bounds, i); } //2.1线切片输出 polygonGrid.CutShapeOrderByGrid(polygonReader, _outDir + _polygonName + @"\"); //3.搜索点 IShpReader pointReader = new ShpReader(_dir + @"\" + _ptName + ".shp"); WebMercatorGrid pointGrid = new WebMercatorGrid(); for (int i = _startLevel; i < _endLevel; i++) { pointGrid.Build(pointReader.Bounds, i); } //3.1线切片输出 pointGrid.CutShapeOrderByGrid(pointReader, _outDir + _ptName + @"\"); _isRunning = false; }
Sprite[] LoadSprites(string filename) { // TODO: Cleanly abstract file type detection if (filename.ToLower().EndsWith("r8")) { var r8 = new R8Reader(FileSystem.Open(filename)); return(r8.Select(a => SheetBuilder.Add(a.Image, a.Size, a.Offset)).ToArray()); } BinaryReader reader = new BinaryReader(FileSystem.OpenWithExts(filename, exts)); var ImageCount = reader.ReadUInt16(); if (ImageCount == 0) { var shp = new ShpTSReader(FileSystem.OpenWithExts(filename, exts)); return(shp.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray()); } else { var shp = new ShpReader(FileSystem.OpenWithExts(filename, exts)); return(shp.Frames.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray()); } }
/// <summary> /// 数据转换 /// </summary> /// <param name="fileList"></param> /// <param name="IsZip"></param> /// <returns></returns> public ConvertResult DataConvert(List <ConvertFileList> fileList, string UserID, string OutputCoordName, bool IsZip) { if (fileList == null || fileList.Count <= 0) { return(new ConvertResult()); } string ConvertFolder = ConfigurationManager.AppSettings["ConvertExprotPath"] + Guid.NewGuid().ToString(); string ConvertTypeName = ""; string OutCoordFile = ""; if (OutputCoordName.ToUpper() != "NULL") { OutCoordFile = GetCoordName(OutputCoordName); } // var fileTypeList = _IDicDataCodeRepository.GetAllList().Where(q => q.DataTypeID == "25159792-cdba-11e7-a735-005056bb1c7e").ToList(); foreach (ConvertFileList f in fileList) { FileInfo ff = new FileInfo(f.PhysicsFilePath); f.ID = Guid.NewGuid().ToString(); f.LogicFileName = ff.Name; f.ConvertResult = 0; try { // 检测文件是否存在 if (!File.Exists(f.PhysicsFilePath)) { f.ConvertMsg = UtilityMessageConvert.Get("转换文件不存在!"); f.ConvertResult = 0; continue; } FileInfo fi = null; // 创建转换保存目录 Directory.CreateDirectory(ConvertFolder); if (!Directory.Exists(ConvertFolder)) { Directory.CreateDirectory(ConvertFolder); } string newFile = ""; // 转换文件 switch (f.FileType) { case 1: ConvertTypeName = UtilityMessageConvert.Get("格式转换").Trim(); try { string[] Files = (string.IsNullOrEmpty(f.ConvertKey)) ? Mapgis2Arcgis(f.PhysicsFilePath) : FileFormatConvert(ff, f.ConvertKey, OutputFormats.ToList()); if (Files != null) { foreach (string s in Files) { fi = new FileInfo(s); if (fi.Extension.ToUpper() != ".LOG") { newFile = ConvertFolder + "\\" + fi.Name; if (f.ConvertFilePath != "") { newFile = f.ConvertFilePath + "\\" + fi.Name; } File.Copy(s, ConvertFolder + "\\" + fi.Name, true); File.Copy(s, newFile, true); } try { File.Delete(s); } catch { } } if (f.ConvertFilePath != "") { f.ConvertFilePath = f.ConvertFilePath + "\\" + f.LogicFileName.Substring(0, f.LogicFileName.IndexOf('.')); } else { f.ConvertFilePath = ConvertFolder + "\\" + f.LogicFileName.Substring(0, f.LogicFileName.IndexOf('.')); } f.ConvertFolder = ConvertFolder; f.ConvertResult = 1; f.ConvertMsg = UtilityMessageConvert.Get("转换成功"); // _logger.Debug(f.LogicFileName + "转换成功"); } else { f.ConvertResult = 0; f.ConvertMsg = UtilityMessageConvert.Get("转换文件失败"); // _logger.Debug(f.LogicFileName + "转换文件失败"); } } catch (Exception ex) { f.ConvertResult = 0; f.ConvertMsg = UtilityMessageConvert.Get("shp文件错误"); // ex.Message; // _logger.Debug(f.LogicFileName + "shp文件错误"); } break; case 2: // 坐标 ConvertTypeName = UtilityMessageConvert.Get("坐标转换").Trim(); fi = new FileInfo(f.PhysicsFilePath); newFile = ConvertFolder + "\\" + fi.Name; if (f.ConvertFilePath != "") { newFile = f.ConvertFilePath + "\\" + fi.Name; } if (f.CoordPoint != null && f.CoordPoint.Length > 0) { CoordTransformHelper ctf = new CoordTransformHelper(); if (f.CoordPoint[0].Contains(',')) { ErrorMsg = (!ctf.ControlPointTransform(f.PhysicsFilePath, newFile, f.CoordName, f.CoordPoint)) ? UtilityMessageConvert.Get("转换失败") : ""; } else { ErrorMsg = (!ctf.SevenParameterTransform(f.PhysicsFilePath, newFile, f.CoordName, f.CoordPoint)) ? UtilityMessageConvert.Get("转换失败") : ""; } } else //维持以前逻辑 { VectorCoordTransform(f.PhysicsFilePath, OutCoordFile, newFile); } if (ErrorMsg.Trim().Length > 0 || InfoMsg.Trim() == UtilityMessageConvert.Get("转换失败")) { f.ConvertFilePath = ""; f.ConvertMsg = UtilityMessageConvert.Get("shp文件错误");// ErrorMsg != "" ? ErrorMsg : InfoMsg; f.ConvertResult = 0; } else { f.ConvertFilePath = newFile; f.ConvertResult = 1; f.ConvertMsg = UtilityMessageConvert.Get("转换成功"); } ErrorMsg = ""; break; case 3: // 投影 ConvertTypeName = UtilityMessageConvert.Get("投影转换".Trim()); fi = new FileInfo(f.PhysicsFilePath); newFile = ConvertFolder + "\\" + fi.Name; if (f.ConvertFilePath != "") { newFile = f.ConvertFilePath + "\\" + fi.Name; } VectorCoordTransform(f.PhysicsFilePath, OutCoordFile, newFile); //iTelluro.DataTools.PrjTransform.VectorCoordTransform(f.PhysicsFilePath, OutCoordFile, newFile, Error, Info); if (ErrorMsg.Trim().Length > 0 || InfoMsg.Trim() == UtilityMessageConvert.Get("转换失败")) { f.ConvertFilePath = ""; f.ConvertMsg = UtilityMessageConvert.Get("shp文件错误"); // ErrorMsg != "" ? ErrorMsg : InfoMsg; f.ConvertResult = 0; } else { f.ConvertFilePath = newFile; f.ConvertResult = 1; f.ConvertMsg = UtilityMessageConvert.Get("转换成功"); } ErrorMsg = ""; break; default: f.ConvertMsg = ""; f.ConvertResult = 0; continue; } } catch (Exception ex) { f.ConvertMsg = ex.Message; f.ConvertResult = 0; } } ConvertResult ret = new ConvertResult(); ret.fileList = fileList; bool bAllFail = true; foreach (var v in fileList) { if (v.ConvertResult == 1) { bAllFail = false; break; } } if (IsZip == true && bAllFail == false) { string DownFile = ConvertTypeName.Replace(" ", "") + "_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".ZIP"; // Guid.NewGuid().ToString() + ".ZIP"; // 压缩转换成功文件 ZipFile.CreateFromDirectory(ConvertFolder, ConfigurationManager.AppSettings["ConvertExprotPath"] + DownFile); try { Directory.Delete(ConvertFolder, true); } catch { } ret.ZipFileName = DownFile; InfoEarthFrame.Core.ConvertFile entity = new ConvertFile(); entity.Id = Guid.NewGuid().ToString(); entity.UserID = UserID; entity.PhysicsFilePath = ConfigurationManager.AppSettings["ConvertExprotPath"] + DownFile; FileInfo fi = new FileInfo(ConfigurationManager.AppSettings["ConvertExprotPath"] + DownFile); entity.FileName = ConvertTypeName + "_" + DateTime.Now.ToString("yyyyMMdd HH:mm"); foreach (ConvertFileList r in ret.fileList) { if (r.ConvertResult == 1) { FileInfo rFi = new FileInfo(r.PhysicsFilePath); entity.ConvertFileNames += rFi.Name.Substring(0, rFi.Name.IndexOf('.')) + ","; } } if (entity.ConvertFileNames.Length > 0) { entity.ConvertFileNames = entity.ConvertFileNames.Remove(entity.ConvertFileNames.Length - 1); } entity.CreateTime = DateTime.Now; entity.FileType = ret.fileList[0].FileType;// FileTypeToNumber(); try { Insert(entity); } catch (Exception ex) { throw ex; } } if (IsZip == true) { // 添加空间参考 for (int i = 0; i < fileList.Count; i++) { if (fileList[i].ConvertResult == 1) { string ff = fileList[i].ConvertFilePath; if (fileList[i].ConvertFilePath.Substring(fileList[i].ConvertFilePath.Length - 3).ToUpper() != "SHP") { ff += ".shp"; } try { ShpReader sr = new ShpReader(ff); string wkt = sr.GetSridWkt(); if (!string.IsNullOrEmpty(wkt)) { SpatialReference srf = new SpatialReference(wkt); string strHTML = srf.__str__().Replace("\n", "<br/>").Replace("[\"", ":").Replace("]", ""); fileList[i].CoordName = wkt.Substring(wkt.IndexOf("\"") + 1, wkt.IndexOf(",") - wkt.IndexOf("\"") - 2); fileList[i].WKT = strHTML; } } catch { fileList[i].CoordName = ""; fileList[i].WKT = ""; } } } } return(ret); }
/// <summary> /// 七参数转换 /// </summary> /// <param name="srcFile">需要转换的Shp文件</param> /// <param name="toWktStr">转换之后的坐标参考字符串</param> /// <param name="args">七参数数组</param> /// <returns></returns> public bool SevenParameterTransform(string srcFile, string tarFile, string toWktStr, string[] args) { /*算法逻辑 * 1、先将矢量文件统一转换成WGS84坐标参考。 * 2、将矢量文件进行7参数转换,只有在WGS84坐标参考下才能进行换算。 * 3、将转换之后的文件再进行一次坐标转换,转换成需要的坐标参考。 */ bool success = false; string tempPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ShpTemp", Guid.NewGuid().ToString()); Directory.CreateDirectory(tempPath); try { //输出文件路径 //tarFile = Path.Combine(Path.GetDirectoryName(srcFile), Path.GetFileNameWithoutExtension(srcFile) + "_T" + Path.GetExtension(srcFile)); if (File.Exists(srcFile)) { //得到WGS84坐标参考字符串 string strkk = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563,AUTHORITY[\"EPSG\",7030]],AUTHORITY[\"EPSG\",6326]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",4326]]"; //string strkk = GetWKTText(toWktStr); //OSGeo.OSR.SpatialReference sr = new OSGeo.OSR.SpatialReference(strwkt); //sr.SetWellKnownGeogCS("EPSG:4326"); //string strkk = string.Empty; //sr.ExportToWkt(out strkk); //判断原始文件是否是WGS84坐标参考,如果是就不进行转换。 ShpReader shpReader = new ShpReader(srcFile); string str = shpReader.GetSridWkt(); string tmpFile = string.Empty; if (!str.Contains("WGS_1984")) { tmpFile = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(srcFile) + "_T" + Path.GetExtension(srcFile)); iTelluro.DataTools.Utility.GIS.CoordTransform.Ogrtransform(str, strkk, srcFile, tmpFile); srcFile = tmpFile; } //进行7参数转换 string tmpFile2 = string.Empty; if (File.Exists(srcFile) && args != null && args.Length == 7) { string argStr = string.Join(",", args); string wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563,AUTHORITY[\"EPSG\",7030]],TOWGS84[" + argStr + "],AUTHORITY[\"EPSG\",6326]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",4326]]"; ShpReader shpReader2 = new ShpReader(srcFile); string str2 = shpReader2.GetSridWkt(); tmpFile2 = Path.Combine(tempPath, Guid.NewGuid().ToString() + "_T" + Path.GetExtension(srcFile)); iTelluro.DataTools.Utility.GIS.CoordTransform.Ogrtransform(str2, wkt, srcFile, tmpFile2); srcFile = tmpFile2; } toWktStr = GetWKTText(toWktStr); //转换成需要的坐标参考 if (!string.IsNullOrEmpty(toWktStr)) { ShpReader shpReader2 = new ShpReader(srcFile); string str2 = shpReader2.GetSridWkt(); iTelluro.DataTools.Utility.GIS.CoordTransform.Ogrtransform(str2, toWktStr, srcFile, tarFile); } //Directory.Delete(tempPath, true); } success = true; } catch (Exception ex) { } return(success); }
/// <summary> /// 批量导入数据 /// </summary> /// <param name="tableName"></param> /// <param name="shpReader"></param> /// <param name="shpAttr"></param> /// <param name="hashTable"></param> /// <returns></returns> public bool ImportTableMulti(string tableName, ShpReader shpReader, List <string> shpAttr, Hashtable hashTable) { string wkt = shpReader.GetSridWkt(); int srid = shpReader.GetSrid(); try { using (NpgsqlConnection sqlConn = new NpgsqlConnection(_connStr)) { sqlConn.Open(); //向表中添加数据 int pFeatureCount = shpReader.GetFeatureCount(); string sqlStr = String.Format("select Max(SID) from {0}", tableName); NpgsqlCommand sqlC = new NpgsqlCommand(sqlStr, sqlConn); object obj = sqlC.ExecuteScalar(); NpgsqlCommand sqlComm = new NpgsqlCommand(); int maxValue = (obj is System.DBNull) ? 0 : Convert.ToInt32(obj); int maxNum = maxValue + 1; string sqlInsert = ""; for (int i = 0; i < pFeatureCount; i++) { string colStr = string.Empty; string valueStr = string.Empty; Dictionary <string, string> attr1 = shpReader.GetOneFeatureAttribute(i, shpAttr); foreach (KeyValuePair <string, string> item in attr1) { colStr += "\"" + item.Key + "\"" + ","; if (hashTable[item.Key].ToString() == "OFTString") { if (item.Value.Contains("'")) { string newValue = item.Value.Replace("'", "''"); valueStr += String.Format("'{0}',", newValue); } else { valueStr += String.Format("'{0}',", item.Value); } } else { if (!string.IsNullOrEmpty(item.Value)) { valueStr += String.Format("{0},", item.Value); } else { valueStr += String.Format("'{0}',", item.Value); } } } colStr = colStr.TrimEnd(','); valueStr = valueStr.TrimEnd(','); string sid = string.Format("{0}", maxNum + i); string geomStr = String.Format("'{0}'", shpReader.GetOneFeatureGeomWkt(i)); if (i == 0) { sqlInsert += String.Format("insert into {0}(sid,geom,{1}) values", tableName, colStr); } sqlInsert += String.Format(" ({2},{3},{4}),", sid, geomStr, valueStr); } sqlInsert = sqlInsert.TrimEnd(',') + ";"; sqlComm.Connection = sqlConn; sqlComm.CommandText = sqlInsert; sqlComm.ExecuteNonQuery(); return(true); } } catch (Exception ex) { return(false); } }
public bool ImportTable(string tableName, ShpReader shpReader, List <string> shpAttr, Hashtable hashTable) { //if (File.Exists(filePath)) //{ // ShpReader shpReader = new ShpReader(filePath); // // 检查矢量文件的有效性 // if (!shpReader.IsValidDataSource()) // { // return false; // } string wkt = shpReader.GetSridWkt(); int srid = shpReader.GetSrid(); try { using (NpgsqlConnection sqlConn = new NpgsqlConnection(_connStr)) { sqlConn.Open(); //向表中添加数据 int pFeatureCount = shpReader.GetFeatureCount(); string sqlStr = String.Format("select Max(SID) from {0}", tableName); NpgsqlCommand sqlC = new NpgsqlCommand(sqlStr, sqlConn); object obj = sqlC.ExecuteScalar(); NpgsqlCommand sqlComm = new NpgsqlCommand(); int maxValue = (obj is System.DBNull) ? 0 : Convert.ToInt32(obj); int maxNum = maxValue + 1; string sqlCStr = string.Empty; for (int i = 0; i < pFeatureCount; i++) { string colStr = string.Empty; try { string valueStr = string.Empty; Dictionary <string, string> attr1 = new Dictionary <string, string>(); if (pFeatureCount > 0) { attr1 = shpReader.GetOneFeatureAttribute(i, shpAttr); } foreach (KeyValuePair <string, string> item in attr1) { colStr += "\"" + item.Key + "\"" + ","; if (hashTable[item.Key].ToString() == "OFTString") { if (item.Value.Contains("'")) { string newValue = item.Value.Replace("'", "''"); valueStr += String.Format("'{0}',", newValue); } else { valueStr += String.Format("'{0}',", item.Value); } } else { if (!string.IsNullOrEmpty(item.Value)) { valueStr += String.Format("{0},", item.Value); } else { valueStr += String.Format("'{0}',", item.Value); } } } colStr = colStr.TrimEnd(','); valueStr = valueStr.TrimEnd(','); string sid = string.Format("{0}", maxNum + i); string geomStr = String.Format("'{0}'", shpReader.GetOneFeatureGeomWkt(i)); //string sqlInsert = String.Format("insert into {0}(sid,geom,{1}) values({2},{3},{4})", tableName, colStr, sid, geomStr, valueStr); //sqlComm.Connection = sqlConn; //sqlComm.CommandText = sqlInsert; //sqlComm.ExecuteNonQuery(); sqlCStr += string.Format("({0},{1},{2}),", sid, geomStr, valueStr); } catch (Exception ex) { Abp.Logging.LogHelper.LogException(ex); //throw ex; } if ((i % _count == 0) || (i == pFeatureCount - 1)) { sqlCStr = sqlCStr.TrimEnd(','); string sqlInsert = String.Format("insert into {0}(sid,geom,{1}) values{2}", tableName, colStr, sqlCStr); //sqlComm.Connection = sqlConn; //sqlComm.CommandText = sqlInsert; //sqlComm.ExecuteNonQuery(); ExceuteSQL(sqlInsert, string.Empty); sqlCStr = string.Empty; } } return(true); } } catch (Exception ex) { Abp.Logging.LogHelper.LogException(ex); return(false); } }
public bool WriteData2Sql(VectorDataType data, out string dataGuid, out string tablename) { if (!File.Exists(data.Filename)) { dataGuid = null; tablename = null; return(false); } string tableName = Path.GetFileNameWithoutExtension(data.Filename).ToUpper(); string filename = Path.GetFileName(data.Filename); ShpReader shpReader = new ShpReader(data.Filename); // 检查矢量文件的有效性 if (!shpReader.IsValidDataSource()) { dataGuid = null; tablename = null; return(false); } // 创建索引表 //if (!IsTableNameExist(_connStr, _geometryColumnsTableName)) //{ // CreateGeometryColumnsTable(_connStr); //} int srid = shpReader.GetSrid(); try { using (NpgsqlConnection sqlConn = new NpgsqlConnection(_connStr)) { sqlConn.Open(); //建表 Dictionary <string, string> attr = shpReader.GetAttributeType(); List <string> shpAttr = new List <string>(); Hashtable hashTable = new Hashtable(); foreach (KeyValuePair <string, string> item in attr) { shpAttr.Add(item.Key); hashTable.Add(item.Key, item.Value); } if (IsTableNameExist(_connStr, tableName)) { NpgsqlCommand NpgsqlCommand = new NpgsqlCommand(string.Format("drop table {0}", tableName.ToUpper()), sqlConn); NpgsqlCommand.ExecuteNonQuery(); } string sqlCommStr = String.Format("CREATE TABLE {0}(SID SERIAL primary key,", tableName); for (int i = 0; i < shpAttr.Count; i++) { string attrName = shpAttr[i]; sqlCommStr += String.Format("{0} {1},", attrName, Utility.GdalTypeToNpSqlType(hashTable[attrName].ToString())); } sqlCommStr += String.Format("geom geometry)"); NpgsqlCommand sqlComm = new NpgsqlCommand(sqlCommStr, sqlConn); sqlComm.ExecuteNonQuery(); //向表中添加数据 int pFeatureCount = shpReader.GetFeatureCount(); string sqlStr = String.Format("select Max(SID) from {0}", tableName); NpgsqlCommand sqlC = new NpgsqlCommand(sqlStr, sqlConn); object obj = sqlC.ExecuteScalar(); int maxValue = (obj is System.DBNull) ? 0 : Convert.ToInt32(obj); int maxNum = maxValue + 1; for (int i = 0; i < pFeatureCount; i++) { try { string sqlInsert = String.Format("insert into {0} values({1},", tableName, maxNum + i); Dictionary <string, string> attr1 = shpReader.GetOneFeatureAttribute(i, shpAttr); foreach (KeyValuePair <string, string> item in attr1) { if (hashTable[item.Key].ToString() == "OFTString") { if (item.Value.Contains("'")) { string newValue = item.Value.Replace("'", "''"); sqlInsert += String.Format("'{0}',", newValue); } else { sqlInsert += String.Format("'{0}',", item.Value); } } else { if (!string.IsNullOrEmpty(item.Value)) { sqlInsert += String.Format("{0},", item.Value); } else { sqlInsert += String.Format("'{0}',", item.Value); } } } sqlInsert += String.Format("'{0}')", shpReader.GetOneFeatureGeomWkt(i)); sqlComm.CommandText = sqlInsert; sqlComm.ExecuteNonQuery(); } catch (Exception ex) { //NpgsqlEventLog. } } } } catch (Exception ex) { using (NpgsqlConnection sqlConn = new NpgsqlConnection(_connStr)) { sqlConn.Open(); string sqlCommStr = string.Format("drop table {0}", tableName.ToUpper()); NpgsqlCommand sqlComm = new NpgsqlCommand(sqlCommStr, sqlConn); sqlComm.ExecuteNonQuery(); sqlConn.Close(); } throw new Exception("NpgsqlVectorDataService:WriteVector出错,错误原因:" + ex.Message); } //zhangheng 2014-06-24 //如果索引表中已有记录,先删除. //DelIndexData(filename); //InsertIntoGeomColmn(_connStr, data.DataGuid, filename, tableName, shpReader.GetDeminsion(), shpReader.GetGeomType(), shpReader.GetSridWkt()); dataGuid = data.DataGuid; tablename = tableName; return(true); }
Sprite[] LoadSprites(string filename) { var shp = new ShpReader(FileSystem.OpenWithExts(filename, exts)); return(shp.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray()); }