예제 #1
0
        void t_Tick(object sender, EventArgs e)
        {
            try
            {
                if (VariableMaintainer.IsNeedRefresh)
                {
                    string       simulationLayerName  = VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name;
                    IRasterLayer simulationImageLayer = new RasterLayerClass();
                    if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression)
                    {
                        simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder + @"\" + simulationLayerName);
                        ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormLogisticCAWizard.SimulationImage);
                    }
                    else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN)
                    {
                        simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder + @"\" + simulationLayerName);
                        ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormANNCAWizard.SimulationImage);
                    }
                    else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT)
                    {
                        simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder + @"\" + simulationLayerName);
                        ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormDTCAWizard.SimulationImage);
                    }

                    IRasterLayer l       = ArcGISOperator.GetRasterLayerByName(simulationLayerName);
                    IRaster2     raster  = simulationImageLayer.Raster as IRaster2;
                    IPnt         fromPnt = new PntClass();
                    fromPnt.SetCoords(0, 0);
                    IPnt blockSize = new PntClass();
                    blockSize.SetCoords(simulationImageLayer.ColumnCount, simulationImageLayer.RowCount);
                    IPixelBlock pixelBlock = ((IRaster)raster).CreatePixelBlock(blockSize);
                    l.Raster.Read(fromPnt, pixelBlock);
                    ((IRasterEdit)l.Raster).Refresh();

                    IActiveView activeView = VariableMaintainer.CurrentFoucsMap as IActiveView;
                    activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                    VariableMaintainer.IsNeedRefresh = false;
                }

                if (VariableMaintainer.IsSimulationFinished)
                {
                    VariableMaintainer.CurrentTimer.Stop();
                    VariableMaintainer.IsSimulationFinished = false;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
예제 #2
0
        /// <summary>
        /// Opens a file dialog and select the reference raster file.
        /// </summary>
        private void openOutputExtentButton_Click(object sender, EventArgs e)
        {
            RasterFileDialog openFileDialog = new RasterFileDialog(FileDialogType.Open);

            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                outputExtentComboBox.Text = openFileDialog.FileName;

                try
                {
                    IRasterLayer rasterLayer = new RasterLayerClass();
                    rasterLayer.CreateFromFilePath(openFileDialog.FileName);
                    ShowExtent(rasterLayer);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Unfortunately, the application meets an error.\n\nSource: {0}\nSite: {1}\nMessage: {2}", ex.Source, ex.TargetSite, ex.Message), "Error");
                    outputExtentComboBox.Text = "";
                }
            }

            this.BringToFront();
        }
예제 #3
0
        private void OpenRasterFile_Click(object sender, EventArgs e)
        {
            string sFileName = null;
            //新建栅格图层
            IRasterLayer pRasterLayer = null;

            pRasterLayer = new RasterLayerClass();
            //取消文件过滤
            mOpenFileDialog.Filter = "所有文件|*.*";
            //打开文件对话框打开事件
            if (mOpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                //从打开对话框中得到打开文件的全路径
                sFileName = mOpenFileDialog.FileName;
                //创建栅格图层
                pRasterLayer.CreateFromFilePath(sFileName);
                //将图层加入到控件中
                mSceneControl.Scene.AddLayer(pRasterLayer, true);

                //将当前视点跳转到栅格图层
                ICamera pCamera = mSceneControl.Scene.SceneGraph.ActiveViewer.Camera;
                //得到范围
                IEnvelope pEenvelop = pRasterLayer.VisibleExtent;
                //添加z轴上的范围
                pEenvelop.ZMin = mSceneControl.Scene.Extent.ZMin;
                pEenvelop.ZMax = mSceneControl.Scene.Extent.ZMax;
                //设置相机
                pCamera.SetDefaultsMBB(pEenvelop);
                mSceneControl.Refresh();
            }
        }
예제 #4
0
        private void button4_Click(object sender, EventArgs e)
        {
            IRasterLayer pRasterLy = new RasterLayerClass();

            pRasterLy.CreateFromFilePath(@"E:\GIS底层实验\WorkSpace\MyAddIn\result.tif");
            Analyze(pRasterLy);
        }
예제 #5
0
        //确认按钮
        private void btnok_Click(object sender, EventArgs e)
        {
            string InputFile     = this.txtyingxiang.Text.Trim();
            string InputSaveFile = txtbaocun.Text.Trim();
            string Inputxml      = txtxml.Text.Trim();
            string proCommand    = this.txtmingling.Text;

            try
            {
                string i1 = @".compile -v '" + proCommand + "\\ApparentReflectanceAlg.pro" + "'";
                this.IDLcom.ExecuteString(i1);
                string i2 = @".compile -v '" + proCommand + "\\Calibration_Alg.pro" + "'";
                this.IDLcom.ExecuteString(i2);
                string i3 = @".compile -v '" + proCommand + "\\NDVIAlg.pro" + "'";
                this.IDLcom.ExecuteString(i3);
                string i4 = @".compile -v '" + proCommand + "\\Coef_GF1.pro" + "'";
                this.IDLcom.ExecuteString(i4);
                string i5 = @".compile -v '" + proCommand + "\\GetDistanceSun2Eart.pro" + "'";
                this.IDLcom.ExecuteString(i5);
                string i6 = @".compile -v '" + proCommand + "\\GetEs.pro" + "'";
                this.IDLcom.ExecuteString(i6);
                string i7 = @".compile -v '" + proCommand + "\\GetXMLNodeValue.pro" + "'";
                this.IDLcom.ExecuteString(i7);
                string i8 = @".compile -v '" + proCommand + "\\RadiometricCalibration.pro" + "'";
                this.IDLcom.ExecuteString(i8);
                string i9 = @".compile -v '" + proCommand + "\\ReadImage_GF1.pro" + "'";
                this.IDLcom.ExecuteString(i9);
                string i10 = @".compile -v '" + proCommand + "\\TianShu.pro" + "'";
                this.IDLcom.ExecuteString(i10);
                string i11 = @".compile -v '" + proCommand + "\\NDVIExct.pro" + "'";
                this.IDLcom.ExecuteString(i11);


                string cm = @"NDVIExct,'" + InputFile + "','" + Inputxml + "','" + InputSaveFile + "'";
                this.IDLcom.ExecuteString(cm);

                MessageBox.Show("执行完毕!");
                if (addresult.Checked == true)
                {
                    if (File.Exists(InputSaveFile))
                    {
                        IRasterLayer rRL = new RasterLayerClass();
                        rRL.CreateFromFilePath(InputSaveFile);
                        ILayer rL = rRL as ILayer;
                        if (rL != null)
                        {
                            m_pMapCtrl.AddLayer(rL);
                        }
                    }
                    else
                    {
                        MessageBox.Show(InputSaveFile + "不存在!");
                    }
                }
            }
            catch
            {
                MessageBox.Show("执行失败!");
            }
        }
예제 #6
0
        /// <summary>
        /// Read the band and pixelType information.
        /// </summary>
        /// <param name="rasterFile">The raster file.</param>
        /// <param name="bandCount">The band count.</param>
        /// <param name="pixelType">Type of the pixel.</param>
        /// <returns><c>true</c> succeed, <c>false</c> failed.</returns>
        public static bool ReadBandAndPixelInfo(string rasterFile, out int bandCount, out string pixelType)
        {
            IRasterLayer pRasterLayer = null;

            try
            {
                pRasterLayer = new RasterLayerClass();
                pRasterLayer.CreateFromFilePath(rasterFile);
                bandCount = pRasterLayer.BandCount;
                IRaster      pRaster      = pRasterLayer.Raster;
                IRasterProps pRasterProps = pRaster as IRasterProps;
                pixelType = MapAPI.GetPixelType(pRasterProps);
                return(true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("读取栅格元数据失败!请检查文件是否损坏:" + rasterFile, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Log.WriteLog(typeof(MapAPI), ex);
                bandCount = -1;
                pixelType = string.Empty;
                return(false);
            }
            finally
            {
                if (pRasterLayer != null)
                {
                    Marshal.ReleaseComObject(pRasterLayer);
                }
            }
        }
예제 #7
0
파일: LayerHelper.cs 프로젝트: zj8487/HyDM
        /// <summary>
        /// 从文件获取栅格图层
        /// </summary>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public static ILayer GetRasterLayer(string strFile)
        {
            if (string.IsNullOrEmpty(strFile) || !File.Exists(strFile))
            {
                return(null);
            }

            //IWorkspaceFactory wsfRaster = new RasterWorkspaceFactoryClass();
            //IRasterWorkspace rwsSource = wsfRaster.OpenFromFile(Path.GetDirectoryName(strFile), 0) as IRasterWorkspace;

            //if (rwsSource == null)
            //    return null;

            //IRasterDataset rDataset = rwsSource.OpenRasterDataset(Path.GetFileName(strFile));
            //IRasterLayer rasterLayer = new RasterLayerClass();
            //rasterLayer.CreateFromDataset(rDataset);

            //return rasterLayer;


            IRasterLayer rasterLayer = new RasterLayerClass();

            rasterLayer.CreateFromFilePath(strFile);

            return(rasterLayer);
        }
예제 #8
0
        /// <summary>
        /// Add new layers to ArcMap.
        /// </summary>
        /// <param name="fileName">The location of raster file.</param>
        /// <param name="activeView"></param>
        public static void AddLayer(string fileName)
        {
            IRasterLayer rasterLayer = new RasterLayerClass();

            rasterLayer.CreateFromFilePath(fileName);
            ArcMap.Document.AddLayer((ILayer)rasterLayer);
            ArcMap.Document.ActiveView.Refresh();
        }
예제 #9
0
파일: frm_Main.cs 프로젝트: 2018wz/ArcGis-
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "tif/tiff File(*.tif;*.tiff)|*.tif;*.tiff|Shape File(*.shp)|*.shp|All Files (*.*)|*.*";
            //openFileDialog1.Filter = "(*.tif)|*.tif|(*raw)|*raw";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string extendName = System.IO.Path.GetExtension(openFileDialog.FileName);
                if (extendName == ".shp")
                {
                    try
                    {
                        OpenVectorFile(openFileDialog.FileName);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("文件格式不支持!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    IRasterLayer rasterLayer = new RasterLayerClass();
                    try
                    {
                        rasterLayer.CreateFromFilePath(openFileDialog.FileName); // fileName指存本地的栅格文件路径
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("文件格式不支持!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    //设置空间坐标系统
                    try
                    {
                        IWorkspaceFactory pRSTWorkspaceFactory = new RasterWorkspaceFactoryClass();
                        IRasterWorkspace  pRSTWorkspace        = (IRasterWorkspace)pRSTWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(openFileDialog.FileName), 0);
                        IGeoDataset       pGeoDataset          = pRSTWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(openFileDialog.FileName)) as IGeoDataset;

                        //设置空间坐标系统
                        ISpatialReference pTifSpatialReference = pGeoDataset.SpatialReference;
                        axMapControl1.SpatialReference = pTifSpatialReference;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    axMapControl1.AddLayer(rasterLayer, 0);
                    axMapControl1.Refresh();
                    axTOCControl1.Update();
                }
            }
            tabControl1.SelectedIndex = 0;
        }
예제 #10
0
        //加载栅格到地图控件中
        public void LoadRaster(List <string> filePath)
        {
            pMxd = ArcMap.Document as IMxDocument;
            pMap = pMxd.FocusMap;
            IRasterLayer pRasterLy = new RasterLayerClass();

            pRasterLy.CreateFromFilePath(filePath[2]);
            pMap.AddLayer(pRasterLy);
            MessageBox.Show("图层加载成功!");
        }
예제 #11
0
        static void Main(string[] Args)
        {
            if (!RuntimeManager.Bind(ProductCode.Engine))
            {
                if (!RuntimeManager.Bind(ProductCode.Desktop))
                {
                    MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
                    Environment.Exit(-1);
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (Args.Length != 1)
            {
                Args = new string[1];

SelectFile:
                OpenFileDialog OFD = new OpenFileDialog()
                {
                    CheckPathExists = true,
                    Multiselect     = false,
                    Title           = "选择栅格底图...",
                };
                if (OFD.ShowDialog() == DialogResult.OK)
                {
                    IRasterLayer lyr = new RasterLayerClass();
                    try
                    {
                        lyr.CreateFromFilePath(OFD.FileName);
                        if (lyr != null)
                        {
                            Args[0] = OFD.FileName;
                        }
                        else
                        {
                            MessageBox.Show("选中的文件不能作为底图,请重新选择。");
                            goto SelectFile;
                        }
                    }
                    catch
                    {
                        MessageBox.Show("选中的文件不能作为底图,请重新选择。");
                        goto SelectFile;
                    }
                }
                else
                {
                    Environment.Exit(-1);
                }
            }

            Application.Run(new MainForm(Args[0]));
        }
예제 #12
0
        private bool GetUniqueValues(string inFile)
        {
            IRasterLayer            pRasterLayer      = null;
            IUniqueValues           pUniqueValues     = null;
            IRasterCalcUniqueValues pCalcUniqueValues = null;

            try
            {
                pRasterLayer = new RasterLayerClass();
                pRasterLayer.CreateFromFilePath(inFile);
                if (!(1 == pRasterLayer.BandCount))
                {
                    XtraMessageBox.Show("文件类型不正确,请选择分类结果文件!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return(false);
                }
                pUniqueValues     = new UniqueValuesClass();
                pCalcUniqueValues = new RasterCalcUniqueValuesClass();
                pCalcUniqueValues.AddFromRaster(pRasterLayer.Raster, 0, pUniqueValues);
                if (_dt.Rows.Count > 0)
                {
                    _dt.Rows.Clear();
                }
                for (int i = 0; i < pUniqueValues.Count; i++)
                {
                    DataRow row = _dt.NewRow();
                    row[0] = pUniqueValues.get_UniqueValue(i);
                    _dt.Rows.Add(row);
                }
                return(true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("读取唯一值失败!\r\n" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Log.WriteLog(typeof(frmRecode), ex);
                return(false);
            }
            finally
            {
                if (pCalcUniqueValues != null)
                {
                    Marshal.ReleaseComObject(pCalcUniqueValues);
                }
                if (pUniqueValues != null)
                {
                    Marshal.ReleaseComObject(pUniqueValues);
                }
                if (pRasterLayer != null)
                {
                    Marshal.ReleaseComObject(pRasterLayer);
                }
            }
        }
예제 #13
0
        private void button3_Click(object sender, EventArgs e)
        {
            string inputFullFilePath  = textBox1.Text;
            string outputFullFilePath = textBox2.Text;
            // deal with the outputFullFilePath
            int    _index                = outputFullFilePath.LastIndexOf("\\");
            string outputRasterName      = (outputFullFilePath.Substring(_index + 1)); //name
            string outputRasterDirectory = outputFullFilePath.Remove(_index);          //directory

            //deal with input
            IRasterLayer pRasterLayer = new RasterLayerClass();

            pRasterLayer.CreateFromFilePath(inputFullFilePath);
            IRaster raster = pRasterLayer.Raster;

            IMapAlgebraOp mapAlgebraOp;

            mapAlgebraOp = new RasterMapAlgebraOpClass();
            //控制raster分析的环境
            IRasterAnalysisEnvironment rasterAnalysisEnvironment = default(IRasterAnalysisEnvironment);

            rasterAnalysisEnvironment = (IRasterAnalysisEnvironment)mapAlgebraOp;

            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(outputRasterDirectory, 0);//这里应该是输出raster的路径

            rasterAnalysisEnvironment.OutWorkspace = workspace;

            try
            {
                mapAlgebraOp.BindRaster((IGeoDataset)raster, "this");
                //定义表达式(elevationMode为要减去的数值)不要忘了"[ ]"
                //"CON(ISNULL([this]),0,[this])"
                //"~(([this]>=92)&([this]<=272))&([this]>=2)"
                string   strOut    = textBox3.Text;
                IRaster  outRaster = (IRaster)mapAlgebraOp.Execute(strOut);
                ISaveAs2 saveAs;
                saveAs = (ISaveAs2)outRaster;
                saveAs.SaveAs(outputRasterName, workspace, "TIFF");//输出名称(注意:名称中加后缀名,例:test.tif),工作空间,格式
                MessageBox.Show("栅格计算器成功!");

                IRasterLayer pRlayer = new RasterLayer();
                pRlayer.CreateFromRaster(outRaster);
                pRlayer.Name = System.IO.Path.GetFileName(outputFullFilePath);
                mainForm.axMapControl1.AddLayer(pRlayer, 0);
            }
            catch (Exception ex)
            {
            }
        }
예제 #14
0
        private void btnok_Click(object sender, EventArgs e)
        {
            string InputFile = null;

            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                if (i + 1 == listBox1.Items.Count)
                {
                    InputFile += "'" + listBox1.Items[i] + "'";
                }
                else
                {
                    InputFile += "'" + listBox1.Items[i] + "',";
                }
            }
            string InputSaveFile = this.txtbaocun.Text.Trim();
            string proCommand    = this.textidl.Text.Trim();

            try
            {
                string paths = @"[" + InputFile + "]";
                this.IDLcom.ExecuteString(@".compile -v '" + proCommand + "'");
                this.IDLcom.ExecuteString(@"LayerStacking," + paths + ",'" + InputSaveFile + "'");
                MessageBox.Show("执行完毕!");

                if (addresult.Checked == true)
                {
                    if (File.Exists(InputSaveFile))
                    {
                        IRasterLayer rRL = new RasterLayerClass();
                        rRL.CreateFromFilePath(InputSaveFile);
                        ILayer rL = rRL as ILayer;
                        if (rL != null)
                        {
                            m_pMapCtrl.AddLayer(rL);
                        }
                    }
                    else
                    {
                        MessageBox.Show(InputSaveFile + "不存在!");
                    }
                }
            }
            catch
            {
                MessageBox.Show("执行失败!");
            }
        }
예제 #15
0
        public void  Create()
        {
            IMap          pMap          = null;
            IFeatureLayer pFeatureLayer = null;
            IRasterLayer  pRasterLayer  = null;

            try
            {
                if (_SourceFile.EndsWith(".shp"))
                {
                    pMap          = new MapClass();
                    pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = EngineAPI.OpenFeatureClass(_SourceFile);
                    pMap.AddLayer(pFeatureLayer);
                    _ExportMan.ExportMapExtent(pMap as IActiveView, new Size(512, 0), _OutFile, 300);
                }
                else
                {
                    pMap         = new MapClass();
                    pRasterLayer = new RasterLayerClass();
                    pRasterLayer.CreateFromFilePath(_SourceFile);
                    pMap.AddLayer(pRasterLayer);
                    IRasterProps pRasterProps = pRasterLayer.Raster as IRasterProps;
                    int          width        = pRasterProps.Width / 10;
                    _ExportMan.ExportMapExtent(pMap as IActiveView, new Size(width, 0), _OutFile, 300);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(typeof(ProductQuickView), ex);
            }
            finally
            {
                if (pMap != null)
                {
                    Marshal.ReleaseComObject(pMap);
                }
                if (pFeatureLayer != null)
                {
                    Marshal.ReleaseComObject(pFeatureLayer);
                }
                if (pRasterLayer != null)
                {
                    Marshal.ReleaseComObject(pRasterLayer);
                }
            }
        }
예제 #16
0
        private void DrawRaster(string file)
        {
            try
            {
                Logger.Debug("Start drawing tile" + file + "...");
                IRasterLayer rl = new RasterLayerClass();
                rl.CreateFromFilePath(file);
                var props = (IRasterProps)rl.Raster;
                props.SpatialReference = _dataSpatialReference;

                if (_needReproject)
                {
                    IRasterGeometryProc rasterGeometryProc = new RasterGeometryProcClass();
                    var missing = Type.Missing;
                    rasterGeometryProc.ProjectFast(_layerSpatialReference, rstResamplingTypes.RSP_NearestNeighbor, ref missing, rl.Raster);
                }

                // Fix for issue "Each 256x256 tile rendering differently causing blockly effect."
                // In 10.1 the StrecthType for rasters seems to have changed from esriRasterStretch_NONE to "Percent Clip",
                // giving color problems with 24 or 32 bits tiles.
                // http://arcbrutile.codeplex.com/workitem/11207
                var image  = new Bitmap(file, true);
                var format = image.PixelFormat;
                if (format == PixelFormat.Format24bppRgb || format == PixelFormat.Format32bppArgb || format == PixelFormat.Format32bppRgb)
                {
                    var rasterRGBRenderer = new RasterRGBRendererClass();
                    ((IRasterStretch2)rasterRGBRenderer).StretchType = esriRasterStretchTypesEnum.esriRasterStretch_NONE;
                    rl.Renderer = rasterRGBRenderer;
                }

                rl.Renderer.ResamplingType = rstResamplingTypes.RSP_BilinearInterpolation;
                // Now set the spatial reference to the dataframe spatial reference!
                // Do not remove this line...
                rl.SpatialReference = _layerSpatialReference;
                //rl.Draw(ESRI.ArcGIS.esriSystem.esriDrawPhase.esriDPGeography, (IDisplay)activeView.ScreenDisplay, null);
                rl.Draw(esriDrawPhase.esriDPGeography, _display, null);
                //activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, trackCancel, env);
                Logger.Debug("End drawing tile.");
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // what to do now...
                // just try to load next tile...
            }
        }
예제 #17
0
        private void btnok_Click(object sender, EventArgs e)
        {
            string InputFile     = this.txtyingxiang.Text.Trim();
            string InputSaveFile = this.txtbaocun.Text.Trim();
            string proCommand    = this.textidl.Text;

            try
            {
                string paths = @"['" + InputFile + "']";



                string i1 = @".compile -v '" + proCommand + "\\InitClassCenter.pro" + "'";
                this.IDLcom.ExecuteString(i1);
                string i2 = @".compile -v '" + proCommand + "\\KmeansAlg.pro" + "'";
                this.IDLcom.ExecuteString(i2);
                string i3 = @".compile -v '" + proCommand + "\\Kmeans.pro" + "'";
                this.IDLcom.ExecuteString(i3);


                this.IDLcom.ExecuteString(@"Kmeans," + paths + ",'" + InputSaveFile + "'");

                MessageBox.Show("执行完毕!");
                if (addresult.Checked == true)
                {
                    if (File.Exists(InputSaveFile))
                    {
                        IRasterLayer rRL = new RasterLayerClass();
                        rRL.CreateFromFilePath(InputSaveFile);
                        ILayer rL = rRL as ILayer;
                        if (rL != null)
                        {
                            m_pMapCtrl.AddLayer(rL);
                        }
                    }
                    else
                    {
                        MessageBox.Show(InputSaveFile + "不存在!");
                    }
                }
            }
            catch
            {
                MessageBox.Show("执行失败!");
            }
        }
예제 #18
0
        /// <summary>
        /// Gets the class value from raster.
        /// </summary>
        /// <param name="inFile">The in file.</param>
        /// <returns>List&lt;System.String&gt;.</returns>
        /// <exception cref="System.Exception">文件类型不正确,请选择分类结果文件!</exception>
        public static List <string> GetClassFromRaster(string inFile)
        {
            IRasterLayer            pRasterLayer      = null;
            IUniqueValues           pUniqueValues     = null;
            IRasterCalcUniqueValues pCalcUniqueValues = null;
            List <string>           classNames        = null;

            try
            {
                pRasterLayer = new RasterLayerClass();
                pRasterLayer.CreateFromFilePath(inFile);
                if (!(1 == pRasterLayer.BandCount))
                {
                    throw new Exception("文件类型不正确,请选择分类结果文件!");
                }
                pUniqueValues     = new UniqueValuesClass();
                pCalcUniqueValues = new RasterCalcUniqueValuesClass();
                pCalcUniqueValues.AddFromRaster(pRasterLayer.Raster, 0, pUniqueValues);
                classNames = new List <string>();
                for (int i = 0; i < pUniqueValues.Count; i++)
                {
                    classNames.Add(pUniqueValues.get_UniqueValue(i).ToString());
                }
                return(classNames);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pCalcUniqueValues != null)
                {
                    Marshal.ReleaseComObject(pCalcUniqueValues);
                }
                if (pUniqueValues != null)
                {
                    Marshal.ReleaseComObject(pUniqueValues);
                }
                if (pRasterLayer != null)
                {
                    Marshal.ReleaseComObject(pRasterLayer);
                }
            }
        }
예제 #19
0
 private void buttonXOK_Click(object sender, EventArgs e)
 {
     try
     {
         string           dempath     = m_DEMPath;
         IRaster          raster      = new RasterClass();
         RasterLayerClass rasterlayer = new RasterLayerClass();
         rasterlayer.CreateFromFilePath(dempath);
         IRaster iRaster     = rasterlayer.Raster;
         string  tinFileName = m_TINPath;
         DEMToTIN(iRaster, tinFileName);
     }
     catch (System.Exception ex)
     {
         MessageBox.Show(ex.Message);
         return;
     }
 }
예제 #20
0
        public override void Draw(esriDrawPhase drawPhase, IDisplay display, ESRI.ArcGIS.esriSystem.ITrackCancel trackCancel)
        {
            var file = @"D:\aaa\strava_issue\2016_1350.png";

            var rl = new RasterLayerClass();

            rl.CreateFromFilePath(file);
            var props = (IRasterProps)rl.Raster;

            props.SpatialReference = new SpatialReferences().GetSpatialReference("urn: ogc:def: crs:EPSG: 6.18.3:3857");
            IRasterGeometryProc3 rasterGeometryProc = new RasterGeometryProcClass();
            var missing = Type.Missing;
            var layerSpatialReference = sp;

            rasterGeometryProc.ProjectFast(layerSpatialReference, rstResamplingTypes.RSP_NearestNeighbor, ref missing, rl.Raster);

            // fix 9/10/2015: with projected tiles color changes and transparency is ignored.
            var image = new Bitmap(file, true);
            // image.MakeTransparent(Color.White);
            //image.Save(@"D:\aaa\strava_issue\2018_1350.png");
            var format = image.PixelFormat;

            if (format == PixelFormat.Format24bppRgb | format == PixelFormat.Format32bppArgb)
            {
                var rasterRgbRenderer = new RasterRGBRendererClass();
                ((IRasterStretch2)rasterRgbRenderer).StretchType = esriRasterStretchTypesEnum.esriRasterStretch_NONE;
                // ((IRasterStretch3)rasterRgbRenderer).UseGamma = true;
                ((IRasterStretch2)rasterRgbRenderer).Background = true;
                ((IRasterStretch3)rasterRgbRenderer).UseGamma   = true;
                var r = new RgbColorClass();
                r.Red   = 49;
                r.Green = 0;
                r.Blue  = 38;
                ((IRasterStretch2)rasterRgbRenderer).BackgroundColor = r;
                //((IRasterStretch2)rasterRgbRenderer).BackgroundColor = r;

                rl.Renderer = rasterRgbRenderer;
            }
            // end fix 9/10/2015: with projected tiles color changes and transparency is ignored.

            rl.Draw(esriDrawPhase.esriDPGeography, display, null);
        }
        public List <ILayer> ReadRasterLayer(List <string> filePathList)
        {
            List <ILayer> layerList = new List <ILayer>();

            if (filePathList.Count == 0)
            {
                return(null);
            }
            else
            {
                foreach (string path in filePathList)
                {
                    IRasterLayer pRasterLayer = new RasterLayerClass();
                    pRasterLayer.CreateFromFilePath(path);
                    layerList.Add(pRasterLayer as ILayer);
                }

                return(layerList);
            }
        }
예제 #22
0
        private void btnExp2Map_Click(object sender, EventArgs e)
        {
            string sTipo = "";
            string sRuta = "";

            if (radioBtnProbabilidad.Checked)
            {
                sTipo = "Probabilidad";
                sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Resultado;
            }
            else if (radioBtnModelo.Checked)
            {
                sTipo = "Modelo";
                sRuta = _sigpi.Parametros.RutaSIGPI + _sigpi.Parametros.Raster;
            }

            if (lvwModelos.SelectedIndices.Count > 0)
            {
                string       sModelo = lvwModelos.SelectedItems[0].Text;
                IMxDocument  pMxDoc  = m_pApp.Document as IMxDocument;
                IMap         pMap    = pMxDoc.FocusMap;
                IRasterLayer pRLayer = new RasterLayerClass();
                pRLayer.CreateFromFilePath(sRuta + "\\" + sModelo);
                AsignarSimbologiaProbabilidad(pRLayer);


                pMap.AddLayer(pRLayer);

                if (pMap.LayerCount > 0)
                {
                    pMap.MoveLayer(pRLayer, pMap.LayerCount - 1);
                }

                pMxDoc.UpdateContents();
                pMxDoc.ActiveView.Refresh();
            }

            //FrmExportMap frmExportMap = new FrmExportMap(_sigpi, lvwModelos.SelectedItems[0].Text, sTipo);
            //frmExportMap.ShowDialog();
        }
예제 #23
0
        /// <summary>
        /// 从文件获取栅格图层
        /// </summary>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public static ILayer GetRasterLayer(string strFile)
        {
            if (string.IsNullOrEmpty(strFile) || !File.Exists(strFile))
                return null;

            //IWorkspaceFactory wsfRaster = new RasterWorkspaceFactoryClass();
            //IRasterWorkspace rwsSource = wsfRaster.OpenFromFile(Path.GetDirectoryName(strFile), 0) as IRasterWorkspace;

            //if (rwsSource == null)
            //    return null;

            //IRasterDataset rDataset = rwsSource.OpenRasterDataset(Path.GetFileName(strFile));
            //IRasterLayer rasterLayer = new RasterLayerClass();
            //rasterLayer.CreateFromDataset(rDataset);

            //return rasterLayer;

            IRasterLayer rasterLayer = new RasterLayerClass();
            rasterLayer.CreateFromFilePath(strFile);

            return rasterLayer;
        }
        private void addtiffile(string tifFilePath, int whichLayer)
        {
            switch (whichLayer)
            {
            case 0:
                UAVFilelist.Add(tifFilePath);
                break;

            case 1:
                RSFilelist.Add(tifFilePath);
                break;
            }
            IRasterLayer rasterLayer = new RasterLayerClass();

            rasterLayer.CreateFromFilePath(tifFilePath); // fileName指存本地的栅格文件路径
            //  RasterBackgroundDisplay(rasterLayer);
            IGroupLayer groupLayer = axMapControl1.get_Layer(whichLayer) as IGroupLayer;

            groupLayer.Add(rasterLayer);
            axTOCControl1.Update();
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }
        /// <summary>
        /// 添加至显示
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <returns></returns>
        public static IRasterLayer AddImgToShow(DataGridView dataGridView)
        {
            IRasterLayer pRasterLayer = new RasterLayerClass();

            try
            {
                int         rowIndex = dataGridView.CurrentCell.RowIndex;
                rasterTable ts       = dataGridView.Rows[rowIndex].DataBoundItem as rasterTable;
                if (ts != null)
                {
                    string imgPath = ts.path.Trim();
                    pRasterLayer = new RasterLayerClass();
                    pRasterLayer.CreateFromFilePath(imgPath);
                }
                return(pRasterLayer);
            }
            catch (Exception exception)
            {
                MessageBox.Show("显示失败,请检查路径或格式是否正确!\n格式为tif或arcgis支持的格式");
                return(null);
            }
        }
예제 #26
0
        private void GetRasterInfo(string file, ref StructProMeta meta)
        {
            IRasterLayer      pRasterLayer         = null;
            ISpatialReference spatialReferenceInfo = null;

            try
            {
                pRasterLayer = new RasterLayerClass();
                pRasterLayer.CreateFromFilePath(_file);
                IRaster      pRaster      = pRasterLayer.Raster;
                IRasterProps pRasterProps = pRaster as IRasterProps;
                meta.Resolution       = pRasterProps.MeanCellSize().X.ToString("f1");
                spatialReferenceInfo  = pRasterProps.SpatialReference;
                meta.CoordinateSystem = spatialReferenceInfo.Name;
                if (spatialReferenceInfo is IProjectedCoordinateSystem)
                {
                    IProjectedCoordinateSystem projectedCoordinateSystem = spatialReferenceInfo as IProjectedCoordinateSystem;
                    meta.MapProjection = projectedCoordinateSystem.Projection.Name;
                    IPoint point = pRasterProps.Extent.UpperLeft;
                    point.Project(projectedCoordinateSystem.GeographicCoordinateSystem);
                    meta.UpperLeftLat = point.Y.ToString();
                    meta.UpperLeftLon = point.X.ToString();
                    point             = pRasterProps.Extent.UpperRight;
                    point.Project(projectedCoordinateSystem.GeographicCoordinateSystem);
                    meta.UpperRightLat = point.Y.ToString();
                    meta.UpperRightLon = point.X.ToString();
                    point = pRasterProps.Extent.LowerRight;
                    point.Project(projectedCoordinateSystem.GeographicCoordinateSystem);
                    meta.LowerRightLat = point.Y.ToString();
                    meta.LowerRightLon = point.X.ToString();
                    point = pRasterProps.Extent.LowerLeft;
                    point.Project(projectedCoordinateSystem.GeographicCoordinateSystem);
                    meta.LowerLeftLat = point.Y.ToString();
                    meta.LowerLeftLon = point.X.ToString();
                }
            }
            catch (Exception)
            { }
        }
예제 #27
0
        private void btnok_Click(object sender, EventArgs e)
        {
            string InputFile     = this.txtyingxiang.Text.Trim();
            string InputSaveFile = this.txtbaocun.Text.Trim();
            string proCommand    = this.textidl.Text;

            try
            {
                this.IDLcom.SetIDLVariable("InputFile", InputFile);
                this.IDLcom.SetIDLVariable("InputSaveFile", InputSaveFile);

                this.IDLcom.ExecuteString(@".compile '" + proCommand + "'");
                this.IDLcom.ExecuteString(@"NDWI0824,InputFile=InputFile,InputSaveFile=InputSaveFile");

                MessageBox.Show("执行完毕!");
                if (addresult.Checked == true)
                {
                    if (File.Exists(InputSaveFile))
                    {
                        IRasterLayer rRL = new RasterLayerClass();
                        rRL.CreateFromFilePath(InputSaveFile);
                        ILayer rL = rRL as ILayer;
                        if (rL != null)
                        {
                            m_pMapCtrl.AddLayer(rL);
                        }
                    }
                    else
                    {
                        MessageBox.Show(InputSaveFile + "不存在!");
                    }
                }
            }
            catch
            {
                MessageBox.Show("执行失败!");
            }
        }
예제 #28
0
        /// <summary>
        /// Gets raster band count.
        /// </summary>
        /// <param name="rasterFile">The raster file.</param>
        /// <returns>System.Int32.</returns>
        public static int GetBandCount(string rasterFile)
        {
            IRasterLayer pRasterLayer = null;

            try
            {
                pRasterLayer = new RasterLayerClass();
                pRasterLayer.CreateFromFilePath(rasterFile);
                return(pRasterLayer.BandCount);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("读取栅格波段失败!请检查文件是否损坏:" + rasterFile, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Log.WriteLog(typeof(MapAPI), ex);
                return(-1);
            }
            finally
            {
                if (pRasterLayer != null)
                {
                    Marshal.ReleaseComObject(pRasterLayer);
                }
            }
        }
예제 #29
0
        private void DrawRaster(string file, IDisplay display)
        {
            try
            {
                var rl = new RasterLayerClass();
                rl.CreateFromFilePath(file);
                var props = (IRasterProps)rl.Raster;
                props.SpatialReference = _dataSpatialReference;

                // Fix for issue "Each 256x256 tile rendering differently causing blockly effect."
                // In 10.1 the StrecthType for rasters seems to have changed from esriRasterStretch_NONE to "Percent Clip",
                // giving color problems with 24 or 32 bits tiles.
                // http://arcbrutile.codeplex.com/workitem/11207
                var image = new Bitmap(file, true);
                var format = image.PixelFormat;
                if (format == PixelFormat.Format24bppRgb || format == PixelFormat.Format32bppArgb || format == PixelFormat.Format32bppRgb)
                {
                    var rasterRGBRenderer = new RasterRGBRendererClass();
                    ((IRasterStretch2)rasterRGBRenderer).StretchType = esriRasterStretchTypesEnum.esriRasterStretch_NONE;
                    rl.Renderer = rasterRGBRenderer;
                }

                rl.Renderer.ResamplingType = rstResamplingTypes.RSP_BilinearInterpolation;
                // Now set the spatial reference to the dataframe spatial reference!
                // Do not remove this line...
                rl.SpatialReference = SpatialReference;
                //rl.Draw(ESRI.ArcGIS.esriSystem.esriDrawPhase.esriDPGeography, (IDisplay)activeView.ScreenDisplay, null);
                rl.Draw(esriDrawPhase.esriDPGeography, display, null);
                //Logger.Debug("End drawing tile.");

            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // what to do now...
                // just try to load next tile...
            }
        }
예제 #30
0
        /// <summary>
        /// 生成等值线
        /// </summary>
        /// <params name="targetworkspace"></params>
        /// <params name="nameOftargetFeatureClass"></params>
        /// <params name="sLayerAliasName"></params>
        private bool CreateContours(IWorkspace targetworkspace, string nameOftargetFeatureClass,
            string sLayerAliasName, string extent, ref string failInfo)
        {
            double douElevation;

            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = 6;
            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            try
            {
                Geoprocessor GP = new Geoprocessor();

                if (withIn(m_strDataFilePath) == false)
                    return false;
                if (TB_Interval.Text == "")
                {
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }
                if (double.TryParse(TB_Interval.Text.Trim(), out douElevation))
                { }
                else
                {
                    TB_Interval.Text = null;
                    MessageBox.Show("请输入正确的等高距!", "提示!");
                    return false;
                }

                string featurOut = m_MakeContoursFolder + "\\Cont.shp";
                int k = 0;
                while (File.Exists(featurOut))
                {
                    k++;
                    featurOut = m_MakeContoursFolder + "\\Cont" + k.ToString() + ".shp";

                }
                int countCont = Directory.GetFiles(m_MakeContoursFolder, "Cont*").Length;
                if (countCont > 0)
                {
                    featurOut = m_MakeContoursFolder + "\\Cont" + countCont.ToString() + ".shp";
                }
                if (DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, m_strDataFilePath, featurOut) == false)
                    return false;
                //执行步长
                this.progressBarControl1.PerformStep();

                string ContourRaster = m_MakeContoursFolder + "\\Spline";
                //string ContourRaster = m_MakeContoursFolder + "\\" + nameOftargetFeatureClass + "_Render";
                if (extent != "")//右上左下  xmax  ymax  xmin  ymin
                    GP.SetEnvironmentValue("Extent", extent);
                bool suc = false;
                string sRasterLayerAliasName = sLayerAliasName + "渲染图";
                ILayer rsLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (rsLayer != null)
                {
                    DataEditCommon.g_pMap.DeleteLayer(rsLayer);
                }
                if (Directory.Exists(ContourRaster))
                {
                    try
                    {
                        Directory.Delete(ContourRaster, true);
                    }
                    catch
                    {
                        k = 1;
                        while (Directory.Exists(ContourRaster))
                        {
                            ContourRaster = m_MakeContoursFolder + "\\Spline" + k.ToString();
                            k++;
                        }
                    }
                }
                switch (CB_InterpolationMethod.Text)
                {
                    case "样条函数插值法":
                        suc = DrawContours.Interpolate2RasterSpline(GP, featurOut, ContourRaster, CB_SplineType.Text);
                        break;
                    case "自然邻域插值法":
                        suc = DrawContours.Interpolate2RasterNN(GP, featurOut, ContourRaster);
                        break;
                    case "克里格插值法":
                        suc = DrawContours.Interpolate2RasterKriging(GP, featurOut, ContourRaster,
                            CB_semiVariogramProp.Text, CB_searchRadiusProp.Text);
                        break;
                    case "反距离权重插值法":
                        suc = DrawContours.Interpolate2RasterIDW(GP, featurOut, ContourRaster);
                        break;
                    case "趋势面插值法":
                        suc = DrawContours.TrendToRaster(GP, featurOut, ContourRaster);
                        break;
                }
                if (suc == false)
                    return false;
                this.progressBarControl1.PerformStep();
                GP = new Geoprocessor();
                string R2Contour = m_MakeContoursFolder + "\\Contour.shp";
                k = 1;
                while (File.Exists(R2Contour))
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + k.ToString() + ".shp";
                    k++;
                }
                int countContour = Directory.GetFiles(m_MakeContoursFolder, "Contour*").Length;
                if (countContour > 0)
                {
                    R2Contour = m_MakeContoursFolder + "\\Contour" + countContour.ToString() + ".shp";
                }

                if (DrawContours.SplineRasterToContour(GP, ContourRaster, R2Contour, douElevation) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                string EvEContour = m_MakeContoursFolder + "\\EvEContour.shp";
                k = 1;
                while (File.Exists(EvEContour))
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + k.ToString() + ".shp";
                    k++;
                }
                int countEvEContour = Directory.GetFiles(m_MakeContoursFolder, "EvEContour*").Length;
                if (countEvEContour > 0)
                {
                    EvEContour = m_MakeContoursFolder + "\\EvEContour" + countEvEContour.ToString() + ".shp";
                }
                if (DrawContours.FeaturesTo3D(GP, R2Contour, EvEContour) == false)
                    return false;
                this.progressBarControl1.PerformStep();

                //获得等值线Shp文件所在的工作空间
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace sourceworkspace = workspaceFactory.OpenFromFile(m_MakeContoursFolder, 0);
                //裁切
                IPolygon bianjie = GetPolygon();

                //导入等值线Shp文件到数据库中
                DrawSpecialCommon drawspecial = new DrawSpecialCommon();
                string nameOfsourceFeatureClass = EvEContour.Substring(EvEContour.LastIndexOf("\\") + 1);
                nameOfsourceFeatureClass = nameOfsourceFeatureClass.Substring(0, nameOfsourceFeatureClass.LastIndexOf("."));
                bool Import = false;
                List<ziduan> list = new List<ziduan>
                {
                    new ziduan("BID", ""),
                    new ziduan("mingcheng", sLayerAliasName),
                    new ziduan("mcid", "0"),
                    new ziduan("date", DateTime.Now.ToString()),
                    new ziduan("type", CB_InterpolationMethod.Text)
                };
                list.Add(new ziduan("BID", ""));
                list.Add(new ziduan("mingcheng", sLayerAliasName));
                list.Add(new ziduan("mcid", "0"));
                list.Add(new ziduan("date", DateTime.Now.ToString()));
                list.Add(new ziduan("type", CB_InterpolationMethod.Text));
                IFeatureLayer pFeatureLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, EditLayerName) as IFeatureLayer;
                string WhereClause = "mcid='" + "0" + "'";

                DataEditCommon.DeleteFeatureByWhereClause(pFeatureLayer, WhereClause);
                if (radioBtnKJ.Checked && bianjie != null)
                    Import = IntersectAll(DataEditCommon.GetFeatureClassByName(sourceworkspace, nameOfsourceFeatureClass), bianjie, list);
                else
                    Import = drawspecial.ShapeImportGDB(sourceworkspace, targetworkspace, nameOfsourceFeatureClass, nameOftargetFeatureClass, list);
                this.progressBarControl1.PerformStep();

                if (Import == false)
                {
                    MessageBox.Show(sLayerAliasName + "导入数据库失败!");
                    DataEditCommon.g_axTocControl.Update();
                    DataEditCommon.g_pAxMapControl.Refresh();
                    failInfo = sLayerAliasName;
                    return false;
                }

                //添加相应的渲染图
                IRasterLayer newRasterLayer = new RasterLayerClass();
                newRasterLayer.CreateFromFilePath(ContourRaster);
                newRasterLayer = IntersectRaster(newRasterLayer, bianjie);
                //newRasterLayer.CreateFromDataset(newRasterDs);
                newRasterLayer.Name = sRasterLayerAliasName;
                UsingRasterStretchColorRampRender(newRasterLayer);
                //groupLayer.Add(newRasterLayer as ILayer);
                int indexPosition = DataEditCommon.g_pAxMapControl.LayerCount;//GroupLayer序号

                //判断MapControl中是否存在该图层
                ILayer mLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, sRasterLayerAliasName);
                if (mLayer != null)
                {
                    DataEditCommon.g_pMyMapCtrl.Map.DeleteLayer(mLayer);
                    indexPosition--;
                }
                DataEditCommon.g_pAxMapControl.AddLayer(newRasterLayer as ILayer, indexPosition);//添加到最下面
                DataEditCommon.g_pAxMapControl.ActiveView.Extent = newRasterLayer.AreaOfInterest;
                DataEditCommon.g_axTocControl.Update();
                DataEditCommon.g_pAxMapControl.Refresh();
                this.progressBarControl1.PerformStep();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }
예제 #31
0
        /// <summary>
        /// 栅格数据转换
        /// </summary>
        public void Tiff(string dirName, string saveName)
        {
            try
            {
                gp.SetEnvironmentValue("workspace", dirName);
                IGpEnumList RasterClasses = gp.ListRasters("", "");
                string rasterClass = RasterClasses.Next();
                while (rasterClass != "")
                {
                    //Msg("开始转换TIFF..." + rasterClass);
                    IRasterLayer rasterLayer = new RasterLayerClass();
                    rasterLayer.CreateFromFilePath(dirName + "\\" + rasterClass);

                    //rasterLayer.SpatialReference = rasterLayer1.SpatialReference;
                    ESRI.ArcGIS.DataManagementTools.CopyRaster copyRaster = new CopyRaster();
                    copyRaster.in_raster = rasterLayer;
                    copyRaster.out_rasterdataset = saveName + "\\" + rasterClass + ".tif";
                    gp.OverwriteOutput = true;
                    gp.Execute(copyRaster, null);
                    Msg(rasterClass + "转换完成!");
                    ras_count++;
                    rasterClass = RasterClasses.Next();
                }
            }
            catch (Exception ex)
            {
                Msg(ex.Message);
            }
        }
예제 #32
0
        //淹没过程导入函数
        public void ymgc(string yxtb, string outPath_Final, string outPath_Mid, string ymgc_tifPath)
        {

            string fail = "";//记录失败数据。
            datetime = DateTime.Now;
            IRasterLayer rasterLayer = new RasterLayerClass();
            ESRI.ArcGIS.DataManagementTools.CopyRaster copyRaster = new CopyRaster();//定义copy工具
            int i = 1, j = 0;
            try
            {
                string aimPh = outPath_Final + "\\" + " ymgc";
                string resultPath = outPath_Mid + "\\" + " ymgc";
                di = new DirectoryInfo(ymgc_tifPath);//
                List<string> Solution = new List<string>();

                
                Hashtable tb = new Hashtable();
               
                FileInfo[] fileOfTIFF = null;
                try
                {
                    string test = tb[yxtb].ToString();
                    fileOfTIFF = di.GetFiles(test + "*.tif");
                }
                catch
                {
                    fileOfTIFF = di.GetFiles("*.tif");
                }


                for (int Count = 0; Count < fileOfTIFF.Length; Count++)
                {
                    int leng_1 = fileOfTIFF[Count].Name.LastIndexOf('_');
                    string te = fileOfTIFF[Count].Name.Substring(0, leng_1);

                    if (Count + 1 == fileOfTIFF.Length)
                    {
                        Solution.Add(te);
                        break;
                    }
                    int leng_2 = fileOfTIFF[Count].Name.LastIndexOf('_');

                    string te1 = fileOfTIFF[Count + 1].Name.Substring(0, leng_2);
                    if (te != te1)
                    {
                        Solution.Add(te);
                    }

                }
                foreach (string fang in Solution)
                {
                    int leng1 = fang.LastIndexOf('-');
                    string fa = fang.Substring(leng1 + 1);
                    //}
                    //for (int fa = 1; fa < Solution.Count; fa++)

                    //    {
                    DateTime datetimeBegain = new DateTime();
                    datetimeBegain = DateTime.Now;
                    //创建一个文件夹
                    //string FA=
                    string create1 = resultPath + fa;
                    importTool.createFolder(create1);
                    Hashtable table = new Hashtable();//创建一个哈希表
                    string projecCode = "";
                    if (tb[yxtb] == null)
                    {
                        projecCode = fang + "*.tif";
                    }
                    else
                        projecCode = tb[yxtb].ToString() + "-" + fa + "*.tif";
                    FileInfo[] arrFi = di.GetFiles(projecCode);
                    max = arrFi.Length;
                    for (int s = 0; s < arrFi.Length; s++)
                    {
                        int length = arrFi[s].Name.LastIndexOf('_');
                        string jq = arrFi[s].Name.Substring(length + 1);//.Replace("_","")
                        string jq2 = jq.Substring(0, jq.Length - 4);//去掉“.tif”
                        double m = double.Parse(jq2);
                        table.Add(m, arrFi[s].Name);
                        j++;
                    }

                    ArrayList akeys = new ArrayList(table.Keys);
                    akeys.Sort();//对哈希表中的关键字排序,排序
                    //DatasourceConnectionInfo info = creatUDB(outPath_Final, "ymgc" + fa.Substring(1), "aaaazzzz");
                    //info.Password = "******";
                    //wks.Datasources.Open(info);
                    DatasourceConnectionInfo info = new DatasourceConnectionInfo();
                    info.Password = set.passWod;
                    info.Server = outPath_Final + "\\" + "ymgc" + fa.Substring(1) + ".udb";
                    foreach (double qq in akeys)
                    {
                        try
                        {
                            rasterLayer.CreateFromFilePath(ymgc_tifPath + "\\" + table[qq].ToString());
                        }
                        catch
                        {
                            fail += table[qq].ToString() + "\n";
                            i = i + 1;
                            continue;
                        }
                        copyRaster.in_raster = rasterLayer;
                        copyRaster.out_rasterdataset = create1 + "\\" + "time" + i.ToString() + ".tif";
                        gp.OverwriteOutput = true;
                        gp.Execute(copyRaster, null);
                        //添加进udb

                        importTool.ImportTIFF(create1 + "\\" + "time" + i.ToString() + ".tif", info);
                        pgrs(i);
                        Msg("方案" + fa + "_time" + i.ToString() + "导入数据源成功");
                        i++;
                    }
                    Msg("项目编号:" + fang + "\n" + "任务总数:" + arrFi.Length + "条\n" + "此次完成:" + (i - 1).ToString() + "条\n" + "处理失败:" + fail);

                    i = 1; max = 1;
                    //wks.Datasources.CloseAll();
                    Msg("用时:" + ExecDateDiff(datetimeBegain, DateTime.Now));
                }
                //Msg("项目编号:" + tb[yxtb].ToString() + "\n" + "任务总数:" + j + "条\n" + "此次完成:" + j.ToString() + "条\n" + "处理失败为:" + fail);
                //Msg("用时:" + ExecDateDiff(datetime, DateTime.Now));
            }
            catch (Exception ex)
            {
                Msg(ex.Message);
            }
        }
        /// <summary>
        /// Where all of the work is done.  Override from TabBaseViewModel
        /// </summary>
        internal override void CreateMapElement()
        {
            try
            {
                IsRunning = true;

                if (!CanCreateElement || ArcMap.Document == null || ArcMap.Document.FocusMap == null || string.IsNullOrWhiteSpace(SelectedSurfaceName))
                {
                    return;
                }

                //base.CreateMapElement();

                var surface = GetSurfaceFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);

                if (surface == null)
                {
                    return;
                }

                // Determine if selected surface is projected or geographic
                ILayer surfaceLayer = GetLayerFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);
                var    geoDataset   = surfaceLayer as IGeoDataset;
                SelectedSurfaceSpatialRef = geoDataset.SpatialReference;

                if (SelectedSurfaceSpatialRef is IGeographicCoordinateSystem)
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.RLOSUserPrompt, VisibilityLibrary.Properties.Resources.RLOSUserPromptCaption);
                    return;
                }

                if (geoDataset != null && ArcMap.Document.FocusMap.SpatialReference.FactoryCode != geoDataset.SpatialReference.FactoryCode)
                {
                    MessageBox.Show(VisibilityLibrary.Properties.Resources.LOSDataFrameMatch, VisibilityLibrary.Properties.Resources.LOSSpatialReferenceCaption);
                    return;
                }

                using (ComReleaser oComReleaser = new ComReleaser())
                {
                    // Create feature workspace
                    IFeatureWorkspace workspace = CreateFeatureWorkspace("tempWorkspace");

                    StartEditOperation((IWorkspace)workspace);

                    // Create feature class
                    IFeatureClass pointFc = CreateObserversFeatureClass(workspace, SelectedSurfaceSpatialRef, "Output" + RunCount.ToString());

                    double finalObserverOffset = GetOffsetInZUnits(ObserverOffset.Value, surface.ZFactor, OffsetUnitType);
                    double finalSurfaceOffset  = GetOffsetInZUnits(SurfaceOffset, surface.ZFactor, OffsetUnitType);

                    double conversionFactor     = GetConversionFactor(SelectedSurfaceSpatialRef);
                    double convertedMinDistance = MinDistance * conversionFactor;
                    double convertedMaxDistance = MaxDistance * conversionFactor;
                    double finalMinDistance     = GetLinearDistance(ArcMap.Document.FocusMap, convertedMinDistance, OffsetUnitType);
                    double finalMaxDistance     = GetLinearDistance(ArcMap.Document.FocusMap, convertedMaxDistance, OffsetUnitType);

                    double finalLeftHorizontalFOV  = GetAngularDistance(ArcMap.Document.FocusMap, LeftHorizontalFOV, AngularUnitType);
                    double finalRightHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, RightHorizontalFOV, AngularUnitType);
                    double finalBottomVerticalFOV  = GetAngularDistance(ArcMap.Document.FocusMap, BottomVerticalFOV, AngularUnitType);
                    double finalTopVerticalFOV     = GetAngularDistance(ArcMap.Document.FocusMap, TopVerticalFOV, AngularUnitType);

                    // Out radius geometries
                    List <IGeometry> radius2GeomList   = new List <IGeometry>();
                    List <IGeometry> radius1_2GeomList = new List <IGeometry>();
                    List <IGeometry> donutGeomList     = new List <IGeometry>();

                    foreach (var observerPoint in ObserverAddInPoints)
                    {
                        // Create buffer geometries for final Min/Max distance
                        ITopologicalOperator topologicalOperator = observerPoint.Point as ITopologicalOperator;
                        IGeometry            geom = topologicalOperator.Buffer(finalMaxDistance);
                        radius2GeomList.Add(geom);
                        radius1_2GeomList.Add(geom);
                        if (finalMinDistance > 0)
                        {
                            IGeometry geom2 = topologicalOperator.Buffer(finalMinDistance);

                            ITopologicalOperator eraseTopo  = geom as ITopologicalOperator;
                            IGeometry            erasedGeom = eraseTopo.Difference(geom2);
                            donutGeomList.Add(erasedGeom);
                        }
                        else
                        {
                            radius1_2GeomList.Add(geom);
                        }

                        double z1 = surface.GetElevation(observerPoint.Point) + finalObserverOffset;

                        //create a new point feature
                        IFeature ipFeature = pointFc.CreateFeature();

                        // Set the field values for the feature
                        SetFieldValues(finalObserverOffset, finalSurfaceOffset, finalMinDistance, finalMaxDistance, finalLeftHorizontalFOV,
                                       finalRightHorizontalFOV, finalBottomVerticalFOV, finalTopVerticalFOV, ipFeature);

                        if (double.IsNaN(z1))
                        {
                            System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.RLOSPointsOutsideOfSurfaceExtent, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                            return;
                        }

                        //Create shape
                        IPoint point = new PointClass()
                        {
                            Z = z1, X = observerPoint.Point.X, Y = observerPoint.Point.Y, ZAware = true
                        };
                        ipFeature.Shape = point;
                        ipFeature.Store();
                    }

                    IFeatureClassDescriptor fd = new FeatureClassDescriptorClass();
                    fd.Create(pointFc, null, "OBJECTID");

                    StopEditOperation((IWorkspace)workspace);

                    try
                    {
                        ILayer layer     = GetLayerFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);
                        string layerPath = GetLayerPath(layer);

                        IFeatureLayer ipFeatureLayer = new FeatureLayerClass();
                        ipFeatureLayer.FeatureClass = pointFc;

                        IDataset ipDataset    = (IDataset)pointFc;
                        string   outputFcName = ipDataset.BrowseName + "_output";
                        string   strPath      = ipDataset.Workspace.PathName + "\\" + ipDataset.BrowseName;
                        string   outPath      = ipDataset.Workspace.PathName + "\\" + outputFcName;

                        IVariantArray parameters = new VarArrayClass();
                        parameters.Add(layerPath);
                        parameters.Add(strPath);
                        parameters.Add(outPath);

                        esriLicenseStatus status = GetSpatialAnalystLicense();
                        if (status == esriLicenseStatus.esriLicenseUnavailable || status == esriLicenseStatus.esriLicenseFailure ||
                            status == esriLicenseStatus.esriLicenseNotInitialized || status == esriLicenseStatus.esriLicenseNotLicensed ||
                            status == esriLicenseStatus.esriLicenseUnavailable)
                        {
                            System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.LOSSpatialAnalystLicenseInvalid, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                            return;
                        }

                        IGeoProcessor2 gp = new GeoProcessorClass();

                        gp.AddOutputsToMap = false;

                        // Add a mask to buffer the output to selected distance
                        SetGPMask(workspace, radius2GeomList, gp, "radiusMask");

                        object oResult = gp.Execute("Visibility_sa", parameters, null);
                        IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult;

                        ComReleaser.ReleaseCOMObject(gp);
                        gp = null;
                        GC.Collect();

                        // Add buffer geometries to the map
                        foreach (IGeometry geom in radius1_2GeomList)
                        {
                            var color = new RgbColorClass()
                            {
                                Blue = 255
                            } as IColor;
                            AddGraphicToMap(geom, color, true);
                        }

                        IRasterLayer outputRasterLayer = new RasterLayerClass();
                        outputRasterLayer.CreateFromFilePath(outPath);

                        string fcName = IntersectOutput(outputRasterLayer, ipDataset, workspace, donutGeomList);

                        IFeatureClass finalFc = workspace.OpenFeatureClass(fcName);

                        IFeatureLayer outputFeatureLayer = new FeatureLayerClass();
                        outputFeatureLayer.FeatureClass = finalFc;

                        //Add it to a map if the layer is valid.
                        if (outputFeatureLayer != null)
                        {
                            // set the renderer
                            IFeatureRenderer featRend = UniqueValueRenderer(workspace, finalFc);
                            IGeoFeatureLayer geoLayer = outputFeatureLayer as IGeoFeatureLayer;
                            geoLayer.Renderer = featRend;
                            geoLayer.Name     = "RLOS_Visibility_" + RunCount.ToString();

                            // Set the layer transparency
                            IDisplayFilterManager      filterManager = (IDisplayFilterManager)outputFeatureLayer;
                            ITransparencyDisplayFilter filter        = new TransparencyDisplayFilter();
                            filter.Transparency         = 80;
                            filterManager.DisplayFilter = filter;

                            ESRI.ArcGIS.Carto.IMap map = ArcMap.Document.FocusMap;
                            map.AddLayer((ILayer)outputFeatureLayer);

                            IEnvelope envelope = outputFeatureLayer.AreaOfInterest.Envelope;
                            ZoomToExtent(envelope);
                        }

                        RunCount += 1;
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                    }

                    //Reset(true);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
            }
            finally
            {
                IsRunning = false;
            }
        }
예제 #34
0
        private void button1_Click(object sender, EventArgs e)
        {
            string myListBoxContent;
            double myCellSize;

            myCellSize = System.Convert.ToDouble(textBox4.Text);
            //try
            {
                myListBoxContent = "正在转换所选ShpFile到栅格数据...";
                textBox3.Text   += myListBoxContent;
                ILayer        selectedLayer        = mainForm.axMapControl1.get_Layer(comboBox1.SelectedIndex);
                IFeatureLayer selectedFeatureLayer = selectedLayer as IFeatureLayer;
                IFeatureClass selectedFeatureClass = selectedFeatureLayer.FeatureClass;
                Geoprocessor  pGeoprocessor        = new Geoprocessor();
                pGeoprocessor.OverwriteOutput = true;

                if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    ESRI.ArcGIS.ConversionTools.PointToRaster pPointToRaster =
                        new ESRI.ArcGIS.ConversionTools.PointToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPointToRaster.cellsize          = myCellSize;
                    pPointToRaster.in_features       = selectedFeatureLayer;
                    pPointToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPointToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPointToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    ESRI.ArcGIS.ConversionTools.PolylineToRaster pPolylineToRaster =
                        new ESRI.ArcGIS.ConversionTools.PolylineToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPolylineToRaster.cellsize          = myCellSize;
                    pPolylineToRaster.in_features       = selectedFeatureLayer;
                    pPolylineToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPolylineToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPolylineToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else if (selectedFeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    ESRI.ArcGIS.ConversionTools.PolygonToRaster pPolygonToRaster =
                        new ESRI.ArcGIS.ConversionTools.PolygonToRaster();
                    pGeoprocessor.SetEnvironmentValue("workspace", myFilePath);
                    pPolygonToRaster.cellsize          = myCellSize;
                    pPolygonToRaster.in_features       = selectedFeatureLayer;
                    pPolygonToRaster.value_field       = selectedFeatureClass.Fields.get_Field(comboBox2.SelectedIndex);
                    pPolygonToRaster.out_rasterdataset = textBox2.Text + ".tif";
                    pGeoprocessor.Execute(pPolygonToRaster, null);
                    myListBoxContent = "转换成功!";
                    textBox3.Text   += Environment.NewLine + Environment.NewLine + myListBoxContent;
                }
                else
                {
                    MessageBox.Show("请选择正确的ShapeFile文件");
                }

                if (MessageBox.Show("是否将生成的新Raster文件添加到图层", "Confirm Message",
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    IRasterLayer myRasterLayer = new RasterLayerClass();
                    try
                    {
                        myRasterLayer.CreateFromFilePath(myFilePath + "\\" + textBox2.Text + ".tif");
                        mainForm.axMapControl1.AddLayer(myRasterLayer, 0);
                    }
                    catch
                    {
                        MessageBox.Show("打开文件错误!");
                    }
                }
            }
        }
예제 #35
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmbSource.Text) || string.IsNullOrEmpty(cmbRegion.Text) || string.IsNullOrEmpty(txtTarget.Text))
            {
                return;
            }
            try
            {
                //得到图层

                ILayer pSourceLayer = ClsGDBDataCommon.GetLayerFromName(m_mapControl.Map, cmbSource.Text);
                ILayer pRegionLayer = ClsGDBDataCommon.GetLayerFromName(m_mapControl.Map, cmbRegion.Text);
                if (pSourceLayer == null || pRegionLayer == null)
                {
                    return;
                }
                if (!(pSourceLayer is IRasterLayer))
                {
                    return;
                }

                IRaster        raster              = ((IRasterLayer)pSourceLayer).Raster;
                IRaster2       raster2             = raster as IRaster2;
                IRasterDataset rasterDatasetSource = raster2.RasterDataset;

                //得到裁切范围
                IGeometry pGeometryRegion = null;
                if (pRegionLayer is IRasterLayer)
                {
                    IRaster     rasterRegion     = ((IRasterLayer)pRegionLayer).Raster;
                    IGeoDataset geoDatasetRegion = rasterRegion as IGeoDataset;
                    IEnvelope   pEnvelope        = geoDatasetRegion.Extent;
                    pGeometryRegion = pEnvelope as IGeometry;
                }
                else if (pRegionLayer is IFeatureLayer)
                {
                    IFeatureLayer featureLayer = pRegionLayer as IFeatureLayer;
                    if (featureLayer.FeatureClass != null)
                    {
                        if (featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            IFeatureCursor pFeatureCursor = featureLayer.FeatureClass.Search(null, false);
                            IFeature       pFeature       = pFeatureCursor.NextFeature();
                            //只裁切出第一个多边形
                            if (pFeature != null)
                            {
                                pGeometryRegion = pFeature.Shape;
                            }
                        }
                    }
                }
                //裁切栅格
                ClsGDBDataCommon cls = new ClsGDBDataCommon();
                cls.RasterSubsetByPolygon(rasterDatasetSource, pGeometryRegion, txtTarget.Text);
                //加到地图中

                IRasterLayer rasterLayerNew = new RasterLayerClass();
                rasterLayerNew.CreateFromFilePath(txtTarget.Text);
                m_mapControl.AddLayer(rasterLayerNew);
                m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            #region 原代码

            //if (cmbSource.SelectedItem != null)
            //{
            //    string itemName = cmbSource.SelectedItem.ToString();
            //    for (int i=0;i<m_mapControl.Map.LayerCount;i++)
            //    {
            //        ILayer pLayer = m_mapControl.Map.get_Layer(i);
            //        if (pLayer.Name==itemName)
            //        {
            //            if(pLayer is IRasterLayer)
            //            {
            //                IDataLayer pDatalayer = pLayer as IDataLayer;
            //                IDatasetName pDname = (IDatasetName)pDatalayer.DataSourceName;

            //                string layername = pDname.WorkspaceName.PathName + "\\" + pDname.Name;
            //                if (!layername.Contains("\\\\"))
            //                {
            //                    m_RasterPath=pDname.WorkspaceName.PathName + "\\" + pDname.Name;
            //                }
            //                else
            //                {
            //                    layername = pDname.WorkspaceName.PathName + pDname.Name;
            //                    m_RasterPath=layername;
            //                }
            //                break;
            //            }
            //        }
            //    }
            //}

            //else
            //{
            //    MessageBox.Show("请选择原始栅格数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            //if (m_ResultPath == null)
            //{
            //    MessageBox.Show("请选择输出路径及文件名", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            //if (cmbRegion.SelectedItem != null)
            //{
            //    //m_ShpPath = comboBoxEx1.SelectedItem.ToString();
            //    string itemName = cmbRegion.SelectedItem.ToString();
            //    for (int i = 0; i < m_mapControl.Map.LayerCount; i++)
            //    {
            //        ILayer pLayer = m_mapControl.Map.get_Layer(i);
            //        if (pLayer.Name == itemName)
            //        {
            //           if(pLayer is IFeatureLayer)
            //           {
            //               IDataLayer pDatalayer = pLayer as IDataLayer;
            //               IDatasetName pDname = (IDatasetName)pDatalayer.DataSourceName;
            //               m_ShpPath=pDname.WorkspaceName.PathName + "\\" + pDname.Name + ".shp";
            //                break;
            //            }
            //        }
            //    }
            //}
            //else
            //{
            //    MessageBox.Show("请选择矢量文件", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            //RasterLayerClass rasterlayer = new RasterLayerClass();
            //rasterlayer.CreateFromFilePath(m_RasterPath);
            //string str = m_ShpPath;
            //string str2 = str.Substring(str.LastIndexOf(@"\") + 1);     //文件名
            //string str3 = str.Substring(0, (str.Length - str2.Length) - 1);  //路径
            //IWorkspaceFactory PWorkSpaceFactory = new ShapefileWorkspaceFactory();
            //IFeatureWorkspace pFeatureWorkSpace = (IFeatureWorkspace)PWorkSpaceFactory.OpenFromFile(str3, 0) ;
            //IFeatureLayer pFeatureLayer = new FeatureLayerClass();
            //pFeatureLayer.FeatureClass = pFeatureWorkSpace.OpenFeatureClass(str2);
            //esriGeometryType pType = pFeatureLayer.FeatureClass.ShapeType;
            //if (pType != esriGeometryType.esriGeometryPolygon)
            //{
            //    MessageBox.Show("矢量文件必须是多边形图层!请重新输入!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            //IFeatureCursor pFeatureCursor = pFeatureLayer.FeatureClass.Search(null, false);
            //IFeature pFeature = pFeatureCursor.NextFeature();
            //IGeometry pGeometry = pFeature.Shape;
            //IPolygon pPolygon = pGeometry as IPolygon;
            //bool result = RasterClip(rasterlayer, pPolygon, m_ResultPath);
            //if (result == true)
            //{
            //    RasterLayerClass prasterlayer = new RasterLayerClass();
            //    rasterlayer.CreateFromFilePath(m_ResultPath + ".tif");
            //    m_mapControl.AddLayer(rasterlayer as ILayer);
            //    m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            //}
            //else
            //{
            //    return;
            //}

            #endregion
        }
예제 #36
0
        private static void DrawRaster(string file)
        {
            try{
                Stopwatch timer = new Stopwatch();
                timer.Start();
                IRasterLayer rl;
                if (!layers.ContainsKey(file)){

                    Logger.Debug("Start drawing tile" + file + "...");
                    rl = new RasterLayerClass();

                    rl.CreateFromFilePath(file);
                    var props = (IRasterProps) rl.Raster;
                    props.SpatialReference = _dataSpatialReference;

                    if (_needReproject){
                        IRasterGeometryProc rasterGeometryProc = new RasterGeometryProcClass();
                        var missing = Type.Missing;
                        rasterGeometryProc.ProjectFast(_layerSpatialReference, rstResamplingTypes.RSP_NearestNeighbor,
                                                       ref missing, rl.Raster);
                    }

                    // Fix for issue "Each 256x256 tile rendering differently causing blockly effect."
                    // In 10.1 the StrecthType for rasters seems to have changed from esriRasterStretch_NONE to "Percent Clip",
                    // giving color problems with 24 or 32 bits tiles.
                    // http://arcbrutile.codeplex.com/workitem/11207
                    var image = new Bitmap(file, true);
                    var format = image.PixelFormat;
                    if (format == PixelFormat.Format24bppRgb || format == PixelFormat.Format32bppRgb){
                        var rasterRGBRenderer = new RasterRGBRendererClass();
                        ((IRasterStretch2) rasterRGBRenderer).StretchType =
                            esriRasterStretchTypesEnum.esriRasterStretch_NONE;
                        rl.Renderer = rasterRGBRenderer;
                    }

                    rl.Renderer.ResamplingType = rstResamplingTypes.RSP_BilinearInterpolation;
                    // Now set the spatial reference to the dataframe spatial reference!
                    // Do not remove this line...
                    rl.SpatialReference = _layerSpatialReference;

                    timer.Stop();
                    Logger.Debug(file + "读取花费时间:" + timer.Elapsed.Milliseconds);
                    layers.Add(file,rl);
                    layerNames.Enqueue(file);
                    if (layerNames.Count > 100){
                        string tempname = layerNames.Dequeue();
                        layers.Remove(tempname);
                    }
                }
                else{
                    layers.TryGetValue(file, out rl);
                    timer.Stop();
                    Logger.Debug(file+"查询花费时间:" + timer.Elapsed.Milliseconds);
                }
                timer.Reset();

                //rl.Draw(ESRI.ArcGIS.esriSystem.esriDrawPhase.esriDPGeography, (IDisplay)activeView.ScreenDisplay, null);
                rl.Draw(esriDrawPhase.esriDPGeography, _display, null);
                //activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, trackCancel, env);
                timer.Stop();
                Logger.Debug(file + "绘制花费时间:" + timer.Elapsed.Milliseconds);
                //Logger.Debug("End drawing tile.");

            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // what to do now...
                // just try to load next tile...
            }
        }
예제 #37
0
        /// <summary>
        /// Opens a file dialog and select the reference raster file.
        /// </summary>
        private void openOutputExtentButton_Click(object sender, EventArgs e)
        {
            RasterFileDialog openFileDialog = new RasterFileDialog(FileDialogType.Open);
            openFileDialog.Multiselect = false;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                outputExtentComboBox.Text = openFileDialog.FileName;

                try
                {
                    IRasterLayer rasterLayer = new RasterLayerClass();
                    rasterLayer.CreateFromFilePath(openFileDialog.FileName);
                    ShowExtent(rasterLayer);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Unfortunately, the application meets an error.\n\nSource: {0}\nSite: {1}\nMessage: {2}", ex.Source, ex.TargetSite, ex.Message), "Error");
                    outputExtentComboBox.Text = "";
                }
            }

            this.BringToFront();
        }
예제 #38
0
        /// <summary>
        /// Where all of the work is done.  Override from TabBaseViewModel
        /// </summary>
        internal override void CreateMapElement()
        {
            if (!CanCreateElement || ArcMap.Document == null || ArcMap.Document.FocusMap == null || string.IsNullOrWhiteSpace(SelectedSurfaceName))
                return;

            //base.CreateMapElement();

            var surface = GetSurfaceFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);

            if (surface == null)
                return;

            using (ComReleaser oComReleaser = new ComReleaser())
            {

                // Create feature workspace
                IFeatureWorkspace workspace = CreateFeatureWorkspace("tempWorkspace");

                StartEditOperation((IWorkspace)workspace);

                // Create feature class
                IFeatureClass pointFc = CreateObserversFeatureClass(workspace, "Output" + RunCount.ToString());

                double finalObserverOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, ObserverOffset.Value, surface.ZFactor, OffsetUnitType);
                double finalSurfaceOffset = GetOffsetInZUnits(ArcMap.Document.FocusMap, SurfaceOffset, surface.ZFactor, OffsetUnitType);

                double conversionFactor = GetConversionFactor(ArcMap.Document.FocusMap.SpatialReference);
                double convertedMinDistance = MinDistance * conversionFactor;
                double convertedMaxDistance = MaxDistance * conversionFactor;
                double finalMinDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMinDistance, OffsetUnitType);
                double finalMaxDistance = GetLinearDistance(ArcMap.Document.FocusMap, convertedMaxDistance, OffsetUnitType);

                double finalLeftHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, LeftHorizontalFOV, AngularUnitType);
                double finalRightHorizontalFOV = GetAngularDistance(ArcMap.Document.FocusMap, RightHorizontalFOV, AngularUnitType);
                double finalBottomVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, BottomVerticalFOV, AngularUnitType);
                double finalTopVerticalFOV = GetAngularDistance(ArcMap.Document.FocusMap, TopVerticalFOV, AngularUnitType);

                // Out radius geometries
                List<IGeometry> radius2GeomList = new List<IGeometry>();
                List<IGeometry> radius1_2GeomList = new List<IGeometry>();
                List<IGeometry> donutGeomList = new List<IGeometry>();

                foreach (var observerPoint in ObserverAddInPoints)
                {
                    // Create buffer geometries for final Min/Max distance
                    ITopologicalOperator topologicalOperator = observerPoint.Point as ITopologicalOperator;
                    IGeometry geom = topologicalOperator.Buffer(finalMaxDistance);
                    radius2GeomList.Add(geom);
                    radius1_2GeomList.Add(geom);
                    if (finalMinDistance > 0)
                    {
                        IGeometry geom2 = topologicalOperator.Buffer(finalMinDistance);

                        ITopologicalOperator eraseTopo = geom as ITopologicalOperator;
                        IGeometry erasedGeom = eraseTopo.Difference(geom2);
                        donutGeomList.Add(erasedGeom);
                    }
                    else
                    {
                        radius1_2GeomList.Add(geom);
                    }

                    double z1 = surface.GetElevation(observerPoint.Point) + finalObserverOffset;

                    //create a new point feature
                    IFeature ipFeature = pointFc.CreateFeature();

                    // Set the field values for the feature
                    SetFieldValues(finalObserverOffset, finalSurfaceOffset, finalMinDistance, finalMaxDistance, finalLeftHorizontalFOV,
                        finalRightHorizontalFOV, finalBottomVerticalFOV, finalTopVerticalFOV, ipFeature);

                    //Create shape
                    IPoint point = new PointClass() { Z = z1, X = observerPoint.Point.X, Y = observerPoint.Point.Y, ZAware = true };
                    ipFeature.Shape = point;
                    ipFeature.Store();
                }

                IFeatureClassDescriptor fd = new FeatureClassDescriptorClass();
                fd.Create(pointFc, null, "OBJECTID");

                StopEditOperation((IWorkspace)workspace);

                try
                {
                    ILayer layer = GetLayerFromMapByName(ArcMap.Document.FocusMap, SelectedSurfaceName);
                    string layerPath = GetLayerPath(layer);

                IFeatureLayer ipFeatureLayer = new FeatureLayerClass();
                ipFeatureLayer.FeatureClass = pointFc;

                IDataset ipDataset = (IDataset)pointFc;
                string outputFcName = ipDataset.BrowseName + "_output";
                string strPath = ipDataset.Workspace.PathName + "\\" + ipDataset.BrowseName;
                string outPath = ipDataset.Workspace.PathName + "\\" + outputFcName;

                IVariantArray parameters = new VarArrayClass();
                    parameters.Add(layerPath);
                parameters.Add(strPath);
                parameters.Add(outPath);

                    esriLicenseStatus status = GetSpatialAnalystLicense();

                    IGeoProcessor2 gp = new GeoProcessorClass();

                    gp.AddOutputsToMap = false;

                    // Add a mask to buffer the output to selected distance
                    SetGPMask(workspace, radius2GeomList, gp, "radiusMask");

                    object oResult = gp.Execute("Visibility_sa", parameters, null);
                    IGeoProcessorResult ipResult = (IGeoProcessorResult)oResult;

                    ComReleaser.ReleaseCOMObject(gp);
                    gp = null;
                    GC.Collect();

                    // Add buffer geometries to the map
                    foreach (IGeometry geom in radius1_2GeomList)
                    {
                        var color = new RgbColorClass() { Blue = 255 } as IColor;
                        AddGraphicToMap(geom, color, true);
                    }

                    IRasterLayer outputRasterLayer = new RasterLayerClass();
                    outputRasterLayer.CreateFromFilePath(outPath);

                    string fcName = IntersectOutput(outputRasterLayer, ipDataset, workspace, donutGeomList);

                    IFeatureClass finalFc = workspace.OpenFeatureClass(fcName);

                    IFeatureLayer outputFeatureLayer = new FeatureLayerClass();
                    outputFeatureLayer.FeatureClass = finalFc;

                    //Add it to a map if the layer is valid.
                    if (outputFeatureLayer != null)
                    {
                        // set the renderer
                        IFeatureRenderer featRend = UnqueValueRenderer(workspace, finalFc);
                        IGeoFeatureLayer geoLayer = outputFeatureLayer as IGeoFeatureLayer;
                        geoLayer.Renderer = featRend;
                        geoLayer.Name = "VisibilityLayer_" + RunCount.ToString();

                        // Set the layer transparency
                        IDisplayFilterManager filterManager = (IDisplayFilterManager)outputFeatureLayer;
                        ITransparencyDisplayFilter filter = new TransparencyDisplayFilter();
             			            filter.Transparency = 80;
             			            filterManager.DisplayFilter = filter;

                        ESRI.ArcGIS.Carto.IMap map = ArcMap.Document.FocusMap;
                        map.AddLayer((ILayer)outputFeatureLayer);
                    }

                    RunCount += 1;
                }
                catch (Exception ex)
                {
                    string exception = ex.ToString();
                    System.Windows.MessageBox.Show(VisibilityLibrary.Properties.Resources.MsgTryAgain, VisibilityLibrary.Properties.Resources.MsgCalcCancelled);
                }

                //Reset(true);
            }
        }