Пример #1
0
        private void IDWInterpolation(IFeatureClass pointFeature, IRaster refRaster, string name)
        {
            IFeatureClassDescriptor pointDescript = new FeatureClassDescriptorClass();

            pointDescript.Create(pointFeature, null, name);
            object                     extend   = (refRaster as IGeoDataset).Extent;
            IRasterProps               refProps = refRaster as IRasterProps;
            object                     cell     = refProps.MeanCellSize().X;
            IInterpolationOp           interpla = new RasterInterpolationOpClass();
            IRasterAnalysisEnvironment IDWEnv   = interpla as IRasterAnalysisEnvironment;

            IDWEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cell);
            IDWEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend);
            IGeoDataset   output = interpla.IDW((IGeoDataset)pointDescript, 2, null, null);
            IGeoDataset   input  = refRaster as IGeoDataset;
            IExtractionOp op     = new RasterExtractionOpClass();

            output = op.Raster(output, input);
            var               clipRaster   = (IRaster)output;
            ISaveAs           pSaveAs      = clipRaster as ISaveAs;
            IWorkspaceFactory workspaceFac = new RasterWorkspaceFactoryClass();
            var               groups       = Regex.Match(name, @"^(\d+)_(\d+)_(\d+)$").Groups;

            name = string.Format("{0:D2}{1:D2}", int.Parse(groups[2].Value), int.Parse(groups[3].Value));
            IDataset outDataset = pSaveAs.SaveAs(fileName + name + ".img", workspaceFac.OpenFromFile(filePath, 0), "IMAGINE Image");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(outDataset);
        }
Пример #2
0
        static void Mosaic(IRasterCatalog rasterCatalog)
        {
            try
            {
                //Mosaics all rasters in the raster catalog to an output raster dataset
                IMosaicRaster mosaicRaster = new MosaicRasterClass();
                mosaicRaster.RasterCatalog = rasterCatalog;

                //Set mosaicking options, you may not need to set these for your data
                mosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_MATCH;
                mosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_LAST;

                //Open output workspace
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace        workspace        = workspaceFactory.OpenFromFile(outputFolder, 0);

                //Save out to a target raster dataset
                //It can be saved to TIFF, IMG, GRID, BMP, GIF, JPEG2000, JPEG, Geodatabase, ect.
                ISaveAs saveas = (ISaveAs)mosaicRaster;
                saveas.SaveAs(outputName, workspace, "TIFF");
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
        }
Пример #3
0
        /// <summary>
        /// Save the edition as a specified file.
        /// </summary>
        /// <param name="fileName">New file path of raster layer to be saved.</param>
        /// <param name="activeLayer">Raster layer to be saved.</param>
        /// <param name="edits">Pixel collection that contains edited pixels.</param>
        public static void SaveEditsAs(string fileName, IRasterLayer activeLayer, PixelCollection edits)
        {
            if (activeLayer == null || edits.Count == 0)
            {
                return;
            }

            //Random rnd = new Random();
            //string tempFile = rnd.Next().ToString();

            ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.EngineOrDesktop);

            // Get the original file
            // IRasterLayer rasterLayer = activeLayer;
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            //IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(rasterLayer.FilePath), 0);
            //IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(rasterLayer.FilePath));

            // Open the new file save location
            IWorkspace mWorkspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0);

            // Save the original file to a new file
            ISaveAs         saveAs         = (ISaveAs)activeLayer.Raster;
            IRasterDataset2 mRasterDataset = (IRasterDataset2)saveAs.SaveAs(System.IO.Path.GetFileName(fileName),
                                                                            mWorkspace,
                                                                            Raster.GetFormat(System.IO.Path.GetExtension(fileName)));
            IRaster mRaster = mRasterDataset.CreateFullRaster();

            // Save edits to file
            Raster.WriteEdits(mRaster, edits);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(mRaster);
        }
Пример #4
0
        /// <summary>
        /// 计算DEM坡向
        /// </summary>
        /// <param name="rasterLayer">输入DEM图层</param>
        /// <param name="outputFullPath">输出坡度图路径,类型为IMAGE,文件名为img</param>
        public void CreateRasterAspect(ILayer rasterLayer, string outputFullPath)
        {
            if (File.Exists(outputFullPath))
            {
                MessageBox.Show(outputFullPath + "已经存在,请重命名");
                return;
            }
            IRasterLayer         rasterLyr     = rasterLayer as IRasterLayer;
            IRaster              raster        = rasterLyr.Raster;
            RasterSurfaceOpClass rasterOpCls   = new RasterSurfaceOpClass();
            IGeoDataset          geoDataset    = raster as IGeoDataset;
            IGeoDataset          outGeodataset = rasterOpCls.Aspect(geoDataset);
            IRaster              pRaster       = outGeodataset as IRaster;

            FileInfo fi      = new FileInfo(outputFullPath);
            string   fileDir = fi.Directory.FullName;
            string   name    = fi.Name;

            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            IWorkspaceFactory pWSF    = new RasterWorkspaceFactoryClass();
            IWorkspace        pWS     = pWSF.OpenFromFile(fileDir, 0);
            ISaveAs           pSaveAs = pRaster as ISaveAs;

            pSaveAs.SaveAs(name, pWS, "IMAGINE Image");
            IRasterLayer rasterLyr2 = new RasterLayerClass();

            rasterLyr2.CreateFromRaster(pRaster);
            rasterLyr2.Name = name;
            m_mapControl.Map.AddLayer(rasterLyr2 as ILayer);
        }
Пример #5
0
        /// <summary>
        /// 栅格分块
        /// </summary>
        /// <param name="pRasterDataset"></param>
        /// <param name="pOutputWorkspace"></param>
        /// <param name="pWidth"></param>
        /// <param name="pHeight"></param>
        public static void CreateTilesFromRasterDataset(IRasterDataset pRasterDataset, IWorkspace pOutputWorkspace, int pWidth, int pHeight)
        {
            IRasterProps pRasterProps = (IRasterProps)pRasterDataset.CreateDefaultRaster();// cast IRaster to IRasterProps
            double       xTileSize    = pRasterProps.MeanCellSize().X *pWidth;
            double       yTileSize    = pRasterProps.MeanCellSize().Y *pHeight;


            int xTileCount = (int)Math.Ceiling((double)pRasterProps.Width / pWidth);
            int yTileCount = (int)Math.Ceiling((double)pRasterProps.Height / pHeight);

            IEnvelope pExtent     = pRasterProps.Extent;
            IEnvelope pTileExtent = new EnvelopeClass();
            ISaveAs   pSaveAs     = null;

            for (int i = 0; i < xTileCount; i++)
            {
                for (int j = 0; j < yTileCount; j++)
                {
                    pRasterProps = (IRasterProps)pRasterDataset.CreateDefaultRaster();

                    pTileExtent.XMin = pExtent.XMin + i * xTileSize;
                    pTileExtent.XMax = pTileExtent.XMin + xTileSize;
                    pTileExtent.YMin = pExtent.YMin + j * yTileSize;
                    pTileExtent.YMax = pTileExtent.YMin + yTileSize;


                    pRasterProps.Height = pHeight;
                    pRasterProps.Width  = pWidth;

                    pRasterProps.Extent = pTileExtent;
                    pSaveAs             = (ISaveAs)pRasterProps;
                    pSaveAs.SaveAs("tile_" + i + "_" + j + ".tif", pOutputWorkspace, "TIFF");
                }
            }
        }
Пример #6
0
        private void button2_Click(object sender, EventArgs e)
        {
            IGeoDataset inGeoDataSet;
            IGeoDataset outGeoDataSet;
            ISurfaceOp  SurfaceOp = new RasterSurfaceOpClass();

            ILayer       layer       = GetLayerByName(comboBox1.SelectedItem.ToString());
            IRasterLayer rasterLayer = layer as IRasterLayer;
            IRaster      raster      = rasterLayer.Raster;

            inGeoDataSet = raster as IGeoDataset;

            outGeoDataSet = SurfaceOp.Aspect(inGeoDataSet);

            try
            {
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(textBox1.Text), 0);
                ISaveAs           pSaveAs    = outGeoDataSet as ISaveAs;
                pSaveAs.SaveAs(System.IO.Path.GetFileName(textBox1.Text), pWorkspace, "TIFF");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            IRasterLayer pRlayer = new RasterLayer();

            pRlayer.CreateFromRaster((IRaster)outGeoDataSet);
            pRlayer.Name = System.IO.Path.GetFileName(textBox1.Text);
            mainForm.axMapControl1.AddLayer(pRlayer, 0);
        }
Пример #7
0
        void SaveLogSourceAsInternal(ILogSource logSource)
        {
            ISaveAs saveAs = logSource.Provider as ISaveAs;

            if (saveAs == null || !saveAs.IsSavableAs)
            {
                return;
            }
            string filename = fileDialogs.SaveFileDialog(new SaveFileDialogParams()
            {
                SuggestedFileName = saveAs.SuggestedFileName ?? "log.txt"
            });

            if (filename == null)
            {
                return;
            }
            try
            {
                saveAs.SaveAs(filename);
            }
            catch (Exception ex)
            {
                alerts.ShowPopup("Error", "Failed to save file: " + ex.Message, AlertFlags.Ok | AlertFlags.WarningIcon);
            }
        }
Пример #8
0
        public static void exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat)   //输出栅格数据
        {
            string            directory        = parth.Substring(0, parth.LastIndexOf("\\"));
            string            name             = parth.Substring(parth.LastIndexOf("\\") + 1);
            IWorkspaceFactory workspaceFac     = new RasterWorkspaceFactoryClass();
            IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2;

            IRasterInfo rasterInfo  = (rasterLayer.Raster as IRawBlocks).RasterInfo;
            IPoint      originPoint = new Point();

            originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y);
            IRasterProps   rasterProps   = rasterLayer.Raster as IRasterProps;
            IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height,
                                                                                rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true) as IRasterDataset2;

            IRaster2 raster2 = rasterDataSet.CreateDefaultRaster() as IRaster2;

            IPnt pntClass = new Pnt();

            pntClass.X = rasterProps.Width;
            pntClass.Y = rasterProps.Height;
            IRasterCursor rasterCursor   = raster2.CreateCursorEx(pntClass);
            IRasterCursor inRasterCursor = (rasterLayer.Raster as IRaster2).CreateCursorEx(pntClass);

            IRasterEdit rasterEdit = raster2 as IRasterEdit;

            if (rasterEdit.CanEdit())
            {
                IPixelBlock3 pixelBlock3   = rasterCursor.PixelBlock as IPixelBlock3;
                IPixelBlock3 inPixelBlock3 = inRasterCursor.PixelBlock as IPixelBlock3;
                System.Array pixels        = (System.Array)rasterMat;
                pixelBlock3.set_PixelData(0, (System.Array)pixels);
                rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pixelBlock3);
            }
            rasterEdit.Refresh();
            IGeoDataset   inDataset   = rasterLayer.Raster as IGeoDataset;
            IGeoDataset   outDataset  = rasterDataSet as IGeoDataset;
            IExtractionOp op          = new RasterExtractionOpClass();
            var           outDataset1 = op.Raster(outDataset, inDataset);
            var           clipRaster  = (IRaster)outDataset1;
            ISaveAs       pSaveAs     = clipRaster as ISaveAs;

            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(raster2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataSet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWorkspace2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFac);
            if (File.Exists(parth))
            {
                File.Delete(parth);
            }
            workspaceFac = new RasterWorkspaceFactoryClass();
            IDataset outdataset = pSaveAs.SaveAs(name, workspaceFac.OpenFromFile(directory, 0), "IMAGINE Image");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(outdataset);
            return;
        }
Пример #9
0
        //保存分析结果
        public static void SaveRasterLayerTofile(IRasterLayer pRasterLayer, string fileName, string strFileExtension = "TIFF")
        {
            IRaster  pRaster  = pRasterLayer.Raster;
            IRaster2 pRaster2 = pRaster as IRaster2;

            ISaveAs pSaveAs = pRaster2 as ISaveAs;

            pSaveAs.SaveAs(fileName, null, strFileExtension);
        }
Пример #10
0
        public void ExportRaster(IRasterDataset rasterDataset, string path, string sFormat, string sName)
        {
            IWorkspaceFactory wsF = new RasterWorkspaceFactoryClass();
            IWorkspace        ws  = wsF.OpenFromFile(path, 0);

            ISaveAs saveAs = rasterDataset as ISaveAs;

            saveAs.SaveAs(sName, ws, sFormat);
        }
Пример #11
0
        public void Execute(string fileName)
        {
            try
            {
                //组合公式
                string expression = "Con(" + root.expression + "," + root.NodeName + "TRUE," + root.NodeName + "FALSE)";
                ExpCombine(root.lChild, root.rChild, ref expression);

                //绑定文件

                IMapAlgebraOp pRSalgebra = new RasterMapAlgebraOpClass();
                foreach (DataRow row in variable.Rows)
                {
                    pRSalgebra.BindRaster(OpenRasterDataset(row[1].ToString()) as IGeoDataset, row[0].ToString());
                }

                IGeoDataset resDataset = pRSalgebra.Execute(expression);
                ISaveAs     pSaveAs    = resDataset as ISaveAs;
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                FileInfo          fInfo        = new FileInfo(fileName);
                IWorkspaceFactory pWKSF03      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace03 = pWKSF03.OpenFromFile(fInfo.DirectoryName, 0);
                if (fInfo.Extension == ".img")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "IMAGINE Image");
                }
                if (fInfo.Extension == ".tif")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "TIFF");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #12
0
        /// <summary>
        /// 合并栅格目录中的所有栅格
        /// </summary>
        /// <param name="pRasterCatalog"></param>
        /// <param name="outputFolder"></param>
        /// <param name="pOutputName"></param>
        public void Mosaic(IRasterCatalog pRasterCatalog, IWorkspace pWorkspace, string pOutputName)
        {
            IMosaicRaster pMosaicRaster = new MosaicRasterClass();

            pMosaicRaster.RasterCatalog = pRasterCatalog;


            pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_MATCH;
            pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_LAST;

            ISaveAs pSaveas = (ISaveAs)pMosaicRaster;

            pSaveas.SaveAs(pOutputName, pWorkspace, "IMAGINE Image");
        }
Пример #13
0
 public bool RasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo, string FileName)
 {
     try
     {
         IRaster       pRaster                      = pRasterLayer.Raster;
         IRasterProps  pProps                       = pRaster as IRasterProps;
         object        cellSizeProvider             = pProps.MeanCellSize().X;
         IGeoDataset   pInputDataset                = pRaster as IGeoDataset;
         IExtractionOp pExtractionOp                = new RasterExtractionOpClass();
         IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
         pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
         object extentProvider = clipGeo.Envelope;
         object snapRasterData = Type.Missing;
         pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
         IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo as IPolygon, true); //裁切操作
         IRaster     clipRaster;                                                                       //裁切后得到的IRaster
         if (pOutputDataset is IRasterLayer)
         {
             IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;
             clipRaster = rasterLayer.Raster;
         }
         else if (pOutputDataset is IRasterDataset)
         {
             IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;
             clipRaster = rasterDataset.CreateDefaultRaster();
         }
         else if (pOutputDataset is IRaster)
         {
             clipRaster = pOutputDataset as IRaster;
         }
         else
         {
             return(false);
         }
         //保存裁切后得到的clipRaster
         //如果直接保存为img影像文件
         IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
         IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(FileName), 0);
         ISaveAs           pSaveAs    = clipRaster as ISaveAs;
         IDataset          pDataset   = pSaveAs.SaveAs(System.IO.Path.GetFileName(FileName) + ".tif", pWorkspace, "TIFF");//以TIF格式保存
         System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset);
         return(true);
         //MessageBox.Show("成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     catch (Exception exp)
     {
         MessageBox.Show(exp.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return(false);
     }
 }
Пример #14
0
        /// <summary>
        /// 混合图斑分类修正
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool ClassMerge()
        {
            //string inFiles = _entropy+ "," + _classPixel+ "," + _classFeature;
            //string exp = "(b1 gt 1.2) * b2 + (b1 le 1.2) * b3";
            //string cmd = BLL.ConstDef.IDL_FUN_BANDMATH + ",'" + inFiles + "','" + _class + "','" + exp + "'";
            //BLL.EnviVars.instance.IdlModel.Execute(cmd);
            string expression = "Con([entropy] > " + _entropyT + ",[pixel],[feature])";

            try
            {
                IMapAlgebraOp pRSalgebra = new RasterMapAlgebraOpClass();
                pRSalgebra.BindRaster(EngineAPI.OpenRasterFile(_entropy) as IGeoDataset, "entropy");
                pRSalgebra.BindRaster(EngineAPI.OpenRasterFile(_classPixel) as IGeoDataset, "pixel");
                pRSalgebra.BindRaster(EngineAPI.OpenRasterFile(_classFeature) as IGeoDataset, "feature");

                IGeoDataset resDataset = pRSalgebra.Execute(expression);
                ISaveAs     pSaveAs    = resDataset as ISaveAs;
                if (File.Exists(_class))
                {
                    File.Delete(_class);
                }
                FileInfo          fInfo        = new FileInfo(_class);
                IWorkspaceFactory pWKSF03      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace03 = pWKSF03.OpenFromFile(fInfo.DirectoryName, 0);
                if (fInfo.Extension == ".img")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "IMAGINE Image");
                }
                if (fInfo.Extension == ".tif")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "TIFF");
                }
                return(true);
            }
            catch (Exception ex)
            { throw ex; }
        }
Пример #15
0
        /// <summary>
        /// Save the extent change into a new raster file.
        /// </summary>
        /// <param name="rasterLayer">Raster layer</param>
        /// <param name="fileName">Path of the output file</param>
        /// <param name="xmin">Minimum X coordinate</param>
        /// <param name="ymin">Minimum Y coordinate</param>
        /// <param name="pixelSize">Pixel size</param>
        public static void SaveExtentAs(IRasterLayer rasterLayer, string fileName, double xmin, double ymin, double pixelSize)
        {
            IRasterProps rasterProps = (IRasterProps)rasterLayer.Raster;
            IEnvelope    extent      = new EnvelopeClass();

            extent.PutCoords(xmin, ymin, xmin + rasterProps.Width * pixelSize, ymin + rasterProps.Height * pixelSize);
            extent.Project(rasterProps.Extent.SpatialReference);
            rasterProps.Extent = extent;

            ISaveAs           saveAs           = (ISaveAs)rasterLayer.Raster;
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IWorkspace        mWorkspace       = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0);

            saveAs.SaveAs(System.IO.Path.GetFileName(fileName),
                          mWorkspace,
                          RasterFile.GetFormat(System.IO.Path.GetExtension(fileName)));
        }
Пример #16
0
        /// <summary>
        /// 保存栅格到本地
        /// </summary>
        /// <param name="raster">IRaster</param>
        /// <param name="fileName">本地路径全名</param>
        /// <returns>0:成功 !=0:失败</returns>
        private int RasterSaveAs(IRaster raster, string fileName)
        {
            int result = 0;

            try
            {
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0);
                ISaveAs           pSaveAs    = raster as ISaveAs;
                pSaveAs.SaveAs(System.IO.Path.GetFileName(fileName), pWorkspace, "IMAGINE Image");
                result = 0;
            }
            catch (Exception ex)
            {
                result = 1;
            }
            return(result);
        }
Пример #17
0
        public static void RasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo)
        {
            IRaster       pRaster                      = pRasterLayer.Raster;
            IRasterProps  pProps                       = pRaster as IRasterProps;
            object        cellSizeProvider             = pProps.MeanCellSize().X;
            IGeoDataset   pInputDataset                = pRaster as IGeoDataset;
            IExtractionOp pExtractionOp                = new RasterExtractionOpClass();
            IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;

            pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
            object extentProvider = clipGeo.Envelope;
            object snapRasterData = Type.Missing;

            pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvMinOf, ref extentProvider, ref snapRasterData);
            //IWorkspaceFactory pWrokspaceFactory = new RasterWorkspaceFactoryClass();
            //if (flag == 0)
            //{
            //    flag++;
            //}
            //if (flag == 1)
            //{
            //    pRasterAnaEnvir.OutWorkspace = pWrokspaceFactory.OpenFromFile("D://temp", 0);
            //}
            IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo, true); //裁切操作
            IRaster     clipRaster     = pOutputDataset as IRaster;                           //裁切后得到的IRaster

            //保存裁切后得到的clipRaster
            //如果直接保存为img影像文件
            IWorkspaceFactory pWKSF    = new RasterWorkspaceFactory();
            SaveFileDialog    savefile = new SaveFileDialog();

            savefile.Title  = "选择输出影像";
            savefile.Filter = "栅格文件(*.tif)|*.tif|栅格文件(*.img)|*.img";
            if (savefile.ShowDialog() == DialogResult.OK)
            {
                IWorkspace pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(savefile.FileName), 0);
                ISaveAs    pSaveAs    = clipRaster as ISaveAs;
                pSaveAs.SaveAs(System.IO.Path.GetFileName(savefile.FileName), pWorkspace, "TIFF");//以img格式保存;
                MessageBox.Show("裁切成功!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Пример #18
0
        private void ShowAndSave(IGeoDataset geoDataset)
        {
            IRasterLayer rasterLayer = new RasterLayerClass();
            IRaster      raster      = new Raster();

            raster = (IRaster)geoDataset;
            rasterLayer.CreateFromRaster(raster);
            try
            {
                rasterLayer.Name = System.IO.Path.GetFileName(textBox1.Text);
                mainForm.axMapControl1.AddLayer((ILayer)rasterLayer, 0);
                mainForm.axMapControl1.ActiveView.Refresh();
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(textBox1.Text), 0);
                ISaveAs           pSaveAs    = raster as ISaveAs;
                pSaveAs.SaveAs(System.IO.Path.GetFileName(textBox1.Text), pWorkspace, "TIFF");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #19
0
        private void button2_Click(object sender, EventArgs e)
        {
            IReclassOp reCla;

            reCla = new RasterReclassOp() as IReclassOp;
            //符号化
            IRemap       pRemap;
            INumberRemap pSRemap;

            pSRemap = new NumberRemap() as INumberRemap;
            for (int i = 1; i <= Convert.ToInt32(comboBox2.SelectedItem.ToString()); i++)
            {
                try
                {
                    string str;
                    str = dataGridView1.Rows[i - 1].Cells[0].Value.ToString();
                    float fValue, tValue;
                    int   p;
                    p = str.LastIndexOf("-");

                    fValue = Convert.ToSingle(str.Substring(0, p));
                    tValue = Convert.ToSingle(str.Substring(p + 1, str.Length - p - 1));
                    pSRemap.MapRange(fValue, tValue, Convert.ToInt32(dataGridView1.Rows[i - 1].Cells[1].Value));
                }
                catch
                {
                    MessageBox.Show("Error!");
                    return;
                }
            }
            pRemap = (IRemap)pSRemap;

            //获取栅格图层
            IRasterLayer play          = (IRasterLayer)GetLayerByName(comboBox1.SelectedItem.ToString());
            IRaster      pRster        = play.Raster;
            IGeoDataset  pOutputRaster = null;

            try
            {
                pOutputRaster = reCla.ReclassByRemap((IGeoDataset)pRster, pRemap, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            try
            {
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(textBox1.Text), 0);
                ISaveAs           pSaveAs    = pOutputRaster as ISaveAs;
                pSaveAs.SaveAs(System.IO.Path.GetFileName(textBox1.Text), pWorkspace, "TIFF");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            IRasterLayer pRlayer = new RasterLayer();

            pRlayer.CreateFromRaster((IRaster)pOutputRaster);
            pRlayer.Name = System.IO.Path.GetFileName(textBox1.Text);
            global.p2DMap.AddLayer(pRlayer);
            global.p3DMap.Scene.AddLayer(pRlayer);
            mainForm.axTOCControl1.Update();
            mainForm.axTOCControl2.Update();
        }
Пример #20
0
        public bool MergePixel(out string msg)
        {
            IMapAlgebraOp     pRSalgebra    = null;
            IRasterDataset    pRuleDataset  = null;
            IRasterDataset    pPixelDataset = null;
            IWorkspaceFactory pWKSF         = null;
            IWorkspace        pWorkspace    = null;
            string            bandDirectory = System.IO.Path.Combine(BLL.ConstDef.PATH_TEMP, DateTime.Now.ToFileTime().ToString());

            try
            {
                Directory.CreateDirectory(bandDirectory);
                List <string> uniqueVlaues = EngineAPI.GetRasterUniqueValue(_Hyper_PurePixel);
                pWKSF      = new RasterWorkspaceFactoryClass();
                pWorkspace = pWKSF.OpenFromFile(bandDirectory, 0);
                for (int i = 0; i < uniqueVlaues.Count; i++)
                {
                    if (uniqueVlaues[i] == "0")
                    {
                        continue;
                    }
                    string condition = "[PURE] == " + uniqueVlaues[i];
                    string exp       = "CON(" + condition + ",[PURE],[RULE])";

                    pRuleDataset  = EngineAPI.OpenRasterDataset(_Hyper_Rule, i);
                    pPixelDataset = EngineAPI.OpenRasterFile(_Hyper_PurePixel);
                    pRSalgebra    = new RasterMapAlgebraOpClass();

                    pRSalgebra.BindRaster(pPixelDataset as IGeoDataset, "PURE");
                    pRSalgebra.BindRaster(pRuleDataset as IGeoDataset, "RULE");

                    IGeoDataset resDataset   = pRSalgebra.Execute(exp);
                    string      bandFileName = "class_" + uniqueVlaues[i] + ".tif";
                    string      bandFile     = System.IO.Path.Combine(bandDirectory, bandFileName);

                    ISaveAs pSaveAs = resDataset as ISaveAs;

                    if (File.Exists(bandFile))
                    {
                        File.Delete(bandFile);
                    }

                    IDataset pDataset = pSaveAs.SaveAs(bandFileName, pWorkspace, "TIFF");
                    if (pDataset != null)
                    {
                        Marshal.ReleaseComObject(pDataset);
                    }
                    if (resDataset != null)
                    {
                        Marshal.ReleaseComObject(resDataset);
                    }
                    if (pSaveAs != null)
                    {
                        Marshal.ReleaseComObject(pSaveAs);
                    }
                }

                //layer stack
                string cmd = "bandcompose,'" + bandDirectory + "','" + _Result + "'";
                BLL.EnviVars.instance.IdlModel.Execute(cmd);
                msg = "";
                return(true);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }
            finally
            {
                if (pRuleDataset != null)
                {
                    Marshal.ReleaseComObject(pRuleDataset);
                }
                if (pPixelDataset != null)
                {
                    Marshal.ReleaseComObject(pPixelDataset);
                }
                if (pRSalgebra != null)
                {
                    Marshal.ReleaseComObject(pRSalgebra);
                }
                if (pWKSF != null)
                {
                    Marshal.ReleaseComObject(pWKSF);
                }
                if (pWorkspace != null)
                {
                    Marshal.ReleaseComObject(pWorkspace);
                }
            }
        }
Пример #21
0
        private void buttonX_ok_Click(object sender, EventArgs e)
        {
            try
            {
                IRasterCollection pRasterCollection = new MosaicRasterClass();
                for (int i = 0; i < listBox1.Items.Count; i++)
                {
                    IRasterLayer prasterlayer = new RasterLayerClass();
                    prasterlayer.CreateFromFilePath(listBox1.Items[i].ToString());
                    pRasterCollection.Append(prasterlayer.Raster);
                }
                IMosaicRaster pMosaicRaster = pRasterCollection as IMosaicRaster;
                switch (cmbox_operatortype.SelectedIndex)
                {
                case 0:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_FIRST;
                    break;

                case 1:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_LAST;
                    break;

                case 2:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_MIN;
                    break;

                case 3:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_MAX;
                    break;

                case 4:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_MEAN;
                    break;

                case 5:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_BLEND;
                    break;

                default:
                    pMosaicRaster.MosaicOperatorType = rstMosaicOperatorType.MT_LAST;
                    break;
                }
                switch (comboBox_colormap.SelectedIndex)
                {
                case 0:
                    pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_FIRST;
                    break;

                case 1:
                    pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_LAST;
                    break;

                case 2:
                    pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_MATCH;
                    break;

                case 3:
                    pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_REJECT;
                    break;

                default:
                    pMosaicRaster.MosaicColormapMode = rstMosaicColormapMode.MM_FIRST;
                    break;
                }
                if (string.IsNullOrEmpty(textBoxX_output.Text) == true)
                {
                    return;
                }
                //如果直接保存为img影像文件
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(textBoxX_output.Text), 0);
                ISaveAs           pSaveAs    = pMosaicRaster as ISaveAs;
                IDataset          pDataset   = pSaveAs.SaveAs(System.IO.Path.GetFileNameWithoutExtension(textBoxX_output.Text) + ".tif", pWorkspace, "TIFF");//以TIF格式保存
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Пример #22
0
        /// <summary>
        /// Calculates the specified veg index.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="inFile">The in file.</param>
        /// <param name="outFile">The out file.</param>
        /// <param name="redIndex">Index of the red.</param>
        /// <param name="nirIndex">Index of the nir.</param>
        /// <param name="blueIndex">Index of the blue.</param>
        /// <param name="land">The land index.</param>
        /// <exception cref="System.Exception">不支持的植被指数</exception>
        public static void Calculate(VegIndex index, string inFile, string outFile, int redIndex, int nirIndex, int blueIndex = -1, float land = -1f)
        {
            IMapAlgebraOp     pRSalgebra = null;
            IGeoDataset       resDataset = null;
            ISaveAs           pSaveAs    = null;
            IWorkspaceFactory pWKSF      = null;
            IWorkspace        pWorkspace = null;
            string            expression = string.Empty;

            try
            {
                pRSalgebra = new RasterMapAlgebraOpClass();
                switch (index)
                {
                case VegIndex.DVI:
                    expression = "[NIR] - [RED]";
                    break;

                case VegIndex.EVI:
                    expression = "2.5 * ([NIR] - [RED]) / ([NIR] + 6.0 * [RED] - 7.5 * [BLUE] + 1)";
                    pRSalgebra.BindRaster(GFS.Common.EngineAPI.OpenRasterDataset(inFile, blueIndex) as IGeoDataset, "BLUE");
                    break;

                case VegIndex.NDVI:
                    expression = "([NIR] - [RED]) / ([NIR] + [RED])";
                    break;

                case VegIndex.RVI:
                    expression = "[NIR] / [RED]";
                    break;

                case VegIndex.SAVI:
                    expression = "([NIR] - [RED]) * (1 + " + land + ") / ([NIR] + [RED] + " + land + ")";
                    break;

                default:
                    throw new Exception("不支持的植被指数");
                }
                pRSalgebra.BindRaster(GFS.Common.EngineAPI.OpenRasterDataset(inFile, redIndex) as IGeoDataset, "RED");
                pRSalgebra.BindRaster(GFS.Common.EngineAPI.OpenRasterDataset(inFile, nirIndex) as IGeoDataset, "NIR");
                resDataset = pRSalgebra.Execute(expression);
                pSaveAs    = resDataset as ISaveAs;
                if (File.Exists(outFile))
                {
                    File.Delete(outFile);
                }
                FileInfo fInfo = new FileInfo(outFile);
                pWKSF      = new RasterWorkspaceFactoryClass();
                pWorkspace = pWKSF.OpenFromFile(fInfo.DirectoryName, 0);
                if (fInfo.Extension == ".img")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace, "IMAGINE Image");
                }
                if (fInfo.Extension == ".tif")
                {
                    pSaveAs.SaveAs(fInfo.Name, pWorkspace, "TIFF");
                }
            }
            catch (Exception ex)
            {
                GFS.BLL.Log.WriteLog(typeof(VegetationIndex), ex);
                throw ex;
            }
            finally
            {
                if (pSaveAs != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pSaveAs);
                }
                if (resDataset != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(resDataset);
                }
                if (pRSalgebra != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pRSalgebra);
                }
                if (pWorkspace != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspace);
                }
                if (pWKSF != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pWKSF);
                }
            }
        }
Пример #23
0
        /// <summary>
        /// 提取信息熵小于阈值的纯净像元.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool ExtractPurePixel(out string msg)
        {
            IMapAlgebraOp  pRSalgebra = null;
            IRasterDataset pRDEntropy = null;
            IRasterDataset pRDClass   = null;

            try
            {
                //运算公式
                string condition = "[ENTROPY] >= " + _Hyper_Entropy_T;
                //string expression = "SETNULL(" + condition +",[CLASS])";
                string expression = "CON(" + condition + ",0,[CLASS])";
                //文件绑定
                pRSalgebra = new RasterMapAlgebraOpClass();
                pRDEntropy = EngineAPI.OpenRasterFile(_Hyper_Entropy);
                pRSalgebra.BindRaster(pRDEntropy as IGeoDataset, "ENTROPY");
                pRDClass = EngineAPI.OpenRasterFile(_Hyper_Class);
                pRSalgebra.BindRaster(pRDClass as IGeoDataset, "CLASS");
                //执行运算
                IGeoDataset resDataset = pRSalgebra.Execute(expression);
                //另存结果
                _Hyper_PurePixel = System.IO.Path.Combine(BLL.ConstDef.PATH_TEMP, "PurePixel_" + DateTime.Now.ToFileTime().ToString() + ".tif");
                ISaveAs pSaveAs = resDataset as ISaveAs;
                if (File.Exists(_Hyper_PurePixel))
                {
                    File.Delete(_Hyper_PurePixel);
                }
                FileInfo          fInfo        = new FileInfo(_Hyper_PurePixel);
                IWorkspaceFactory pWKSF03      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace03 = pWKSF03.OpenFromFile(fInfo.DirectoryName, 0);
                if (fInfo.Extension == ".img")
                {
                    IDataset pDataset = pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "IMAGINE Image");
                    Marshal.ReleaseComObject(pDataset);
                }
                if (fInfo.Extension == ".tif")
                {
                    IDataset pDataset = pSaveAs.SaveAs(fInfo.Name, pWorkspace03, "TIFF");
                    Marshal.ReleaseComObject(pDataset);
                }
                if (resDataset != null)
                {
                    Marshal.ReleaseComObject(resDataset);
                }
                if (pSaveAs != null)
                {
                    Marshal.ReleaseComObject(pSaveAs);
                }
                msg = "";
                return(true);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }
            finally
            {
                if (pRDClass != null)
                {
                    Marshal.ReleaseComObject(pRDClass);
                }
                if (pRDEntropy != null)
                {
                    Marshal.ReleaseComObject(pRDEntropy);
                }
                if (pRSalgebra != null)
                {
                    Marshal.ReleaseComObject(pRSalgebra);
                }
            }
        }
Пример #24
0
        /// <summary>
        /// 根据范围提取数据
        /// </summary>
        /// <param name="pFileName">目标数据名称(不包含路径)</param>
        /// <param name="clipExtent">几何范围</param>
        /// <param name="pDesWS">目标数据工作空间</param>
        /// <param name="format">目标数据类型</param>
        /// <param name="pResRatser">源栅格数据</param>
        /// <param name="bIn">true:表明提取几何范围内部的数据;false:提取几何范围外部的数据</param>
        /// <param name="eError"></param>
        private void StractData(string pFileName, IGeometry clipExtent, IWorkspace pDesWS, string format, IRaster pResRatser, bool bIn, out Exception eError)
        {
            eError = null;
            IExtractionOp extraction = new RasterExtractionOpClass();

            #region 进行裁切
            IGeoDataset      pOrgGeoDt  = pResRatser as IGeoDataset;
            IGeoDataset      pDesGeoDt  = null;
            IPolygon         pPoly      = clipExtent as IPolygon;
            ICircularArc     pArc       = clipExtent as ICircularArc;
            IPointCollection pPointColl = clipExtent as IPointCollection;
            IEnvelope        pRec       = clipExtent as IEnvelope;
            if (pPoly != null)
            {
                //几何范围是多边形
                pDesGeoDt = extraction.Polygon(pOrgGeoDt, pPoly, checkBoxClip.Checked);
            }
            else if (pArc != null)
            {
                //几何范围是圆形

                pDesGeoDt = extraction.Circle(pOrgGeoDt, pArc, checkBoxClip.Checked);
            }
            else if (pRec != null)
            {
                //几何范围是矩形

                pDesGeoDt = extraction.Rectangle(pOrgGeoDt, pRec, checkBoxClip.Checked);
            }
            else if (pPointColl != null)
            {
                //几何范围是点集

                pDesGeoDt = extraction.Points(pOrgGeoDt, pPointColl, checkBoxClip.Checked);
            }
            #endregion

            #region 进行保存
            IRaster pDesRaster = pDesGeoDt as IRaster;
            ISaveAs pSaveAs    = pDesRaster as ISaveAs;
            if (format == "TIF")
            {
                if (!pSaveAs.CanSaveAs("TIFF"))
                {
                    eError = new Exception("该栅格数据不能保存为tiff格式!");
                    return;
                }
                pSaveAs.SaveAs(pFileName, pDesWS, "TIFF");
            }
            else if (format == "IMG")
            {
                if (!pSaveAs.CanSaveAs("IMAGINE Image"))
                {
                    eError = new Exception("该栅格数据不能保存为IMG格式!");
                    return;
                }
                pSaveAs.SaveAs(pFileName, pDesWS, "IMAGINE Image");
            }
            else
            {
                //geodatabase结构数据需要用另外的方式来保存数据:PDB、GDB
                //geodatabase根据已有的rasterDataset生成目标rasterDataset(clipExtent几何限制条件没用上)
                IRaster2 pOrgRaster2 = pResRatser as IRaster2;
                if (pOrgRaster2 == null)
                {
                    return;
                }
                IRasterDataset mOrgRDataset = pOrgRaster2.RasterDataset; //源栅格数据集
                if (mOrgRDataset.CanCopy())
                {
                    mOrgRDataset.Copy(m_DesRasterCollName, pDesWS);
                }
            }
            #endregion
        }
Пример #25
0
        public void RasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo, string FileName)
        {
            try
            {
                //IRaster pRaster = pRasterLayer.Raster;

                //IRasterProps pProps = pRaster as IRasterProps;

                //object cellSizeProvider = pProps.MeanCellSize().X;

                //IGeoDataset pInputDataset = pRaster as IGeoDataset;

                //IExtractionOp2 pExtractionOp = new ESRI.ArcGIS.SpatialAnalyst.RasterExtractionOpClass();

                //IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;

                //pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);

                //object extentProvider = clipGeo.Envelope;

                //object snapRasterData = Type.Missing;

                //pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);


                IRasterProps pProps           = pRasterLayer.Raster  as IRasterProps;
                object       cellSizeProvider = pProps.MeanCellSize().X;
                IGeoDataset  pInputDataset    = pRasterLayer.Raster as IGeoDataset;

                //IGeoDataset pInputDataset = pRasterDataset as IGeoDataset;//此种方式也只是得到前3个波段

                //设置格格处理环境
                IExtractionOp2             pExtractionOp   = new RasterExtractionOpClass();
                IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
                pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);

                object extentProvider = clipGeo.Envelope;
                object snapRasterData = Type.Missing;
                pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);



                IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo as IPolygon, true);//裁切操作
                //  IGeoDataset pOutputDataset = pExtractionOp.Rectangle(pInputDataset, clipGeo.Envelope, true);

                IRaster clipRaster; //裁切后得到的IRasterzzz

                if (pOutputDataset is IRasterLayer)
                {
                    IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;

                    clipRaster = rasterLayer.Raster;
                }

                else if (pOutputDataset is IRasterDataset)
                {
                    IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;

                    clipRaster = rasterDataset.CreateDefaultRaster();
                }

                else if (pOutputDataset is IRaster)
                {
                    clipRaster = pOutputDataset as IRaster;
                    //增加阈值设定
                    IRasterProps temRastPro = clipRaster as IRasterProps;
                    temRastPro.NoDataValue = pProps.NoDataValue;
                    //  temRastPro.PixelType = pProps.PixelType;
                }

                else
                {
                    return;
                }

                //保存裁切后得到的clipRaster

                //如果直接保存为img影像文件

                IWorkspaceFactory pWKSF = new RasterWorkspaceFactoryClass();

                IWorkspace pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(FileName), 0);

                ISaveAs pSaveAs = clipRaster as ISaveAs;

                //bool cansave = pSaveAs.CanSaveAs("TIFF");
                bool cansave = pSaveAs.CanSaveAs("BMP");
                bool zzz     = cansave;

                IRasterDataset pRD = pSaveAs.SaveAs(System.IO.Path.GetFileName(FileName), pWorkspace, "TIFF") as IRasterDataset;//以img格式保存

                //Note, SaveAs will return a RasterDataset, to prevent from ISaveAs holding the output,
                //.NET ReleaseCOMObject needs to be called to release the referene to the output raster dataset:
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(outRasterDS);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRD);


                MessageBox.Show("\"" + FileName + "\"成功!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exp)
            {
                MessageBox.Show("截取样本失败!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Пример #26
0
        public bool RasterSubsetByPolygon(IRasterDataset pRasterDataset, IPolygon clipGeo, string FileName)
        {
            try
            {
                IRasterBandCollection rasterBands = pRasterDataset as IRasterBandCollection;
                int nBandCount = rasterBands.Count;
                //设置输出栅格参数
                IRasterLayer rasterLayer = new RasterLayerClass();
                rasterLayer.CreateFromDataset(pRasterDataset);
                IRaster pRaster = rasterLayer.Raster;//此处只得到前3个波段
                IRasterBandCollection bandsNew = pRaster as IRasterBandCollection;
                IRasterBand           pBand    = null;

                for (int i = 3; i < nBandCount; i++)
                {
                    pBand = rasterBands.Item(i);
                    bandsNew.AppendBand(pBand);
                }

                IRasterProps pProps           = pRaster as IRasterProps;
                object       cellSizeProvider = pProps.MeanCellSize().X;
                IGeoDataset  pInputDataset    = pRaster as IGeoDataset;

                //IGeoDataset pInputDataset = pRasterDataset as IGeoDataset;//此种方式也只是得到前3个波段

                //设置格格处理环境
                IExtractionOp2             pExtractionOp   = new RasterExtractionOpClass();
                IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
                pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);

                object extentProvider = clipGeo.Envelope;
                object snapRasterData = Type.Missing;
                pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);

                IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo as IPolygon, true); //裁切操作

                IRaster clipRaster;                                                                           //裁切后得到的IRaster
                if (pOutputDataset is IRasterLayer)
                {
                    IRasterLayer rasterLayer2 = pOutputDataset as IRasterLayer;
                    clipRaster = rasterLayer.Raster;
                }
                else if (pOutputDataset is IRasterDataset)
                {
                    IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;
                    clipRaster = rasterDataset.CreateDefaultRaster();
                }
                else if (pOutputDataset is IRaster)
                {
                    clipRaster = pOutputDataset as IRaster;
                    IRasterProps temRastPro = clipRaster as IRasterProps;
                    temRastPro.NoDataValue = pProps.NoDataValue;
                    temRastPro.PixelType   = rstPixelType.PT_UCHAR;
                }
                else
                {
                    return(false);
                }
                //保存裁切后得到的clipRaster
                //如果直接保存为img影像文件
                //判断保存类型
                string strFileType = System.IO.Path.GetExtension(FileName);
                switch (strFileType.ToUpper())
                {
                case "TIF":
                    strFileType = "TIFF";
                    break;

                case "IMG":
                    strFileType = "IMAGINE Image";
                    break;

                default:
                    strFileType = "TIFF";
                    break;
                }
                IWorkspaceFactory pWKSF      = new RasterWorkspaceFactoryClass();
                IWorkspace        pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(FileName), 0);
                ISaveAs           pSaveAs    = clipRaster as ISaveAs;
                IDataset          pDataset   = pSaveAs.SaveAs(FileName, pWorkspace, strFileType);//以TIF格式保存
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset);
                MessageBox.Show("\"" + FileName + "\"成功!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(true);
                //MessageBox.Show("成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(false);
            }
        }
Пример #27
0
        public void Init()
        {
            //遍历子节点读取参数

            foreach (XmlNode xnl1 in m_xmlnode.ChildNodes)
            {
                if (xnl1 is XmlComment)
                {
                    continue;
                }


                XmlElement xe = (XmlElement)xnl1;
                if (xe.Name == "inputSHPPath")
                {
                    m_input_shppath = xe.InnerText;
                }
            }
            //裁剪的实现
            try
            {
                //获取矢量文件的路径和文件名字
                string   fileN    = m_input_shppath;
                FileInfo fileInfo = new FileInfo(fileN);
                string   filePath = fileInfo.DirectoryName;
                string   fileName = fileInfo.Name;

                //根据选择的矢量文件的路径打开工作空间
                IWorkspaceFactory wsf          = new ShapefileWorkspaceFactory();
                IWorkspace        wp           = wsf.OpenFromFile(filePath, 0);
                IFeatureWorkspace fw           = (IFeatureWorkspace)wp;
                IFeatureClass     featureClass = fw.OpenFeatureClass(fileName);

                //构造一个剪裁过滤器
                IClipFilter2 clipRaster = new ClipFilterClass();
                clipRaster.ClippingType = esriRasterClippingType.esriRasterClippingOutside;
                //将矢量数据的几何属性加到过滤器中
                IGeometry clipGeometry;
                IFeature  feature;

                //将矢量数据中的每一个IFeature几何形状添加到clipGeometry
                for (int i = 0; i < featureClass.FeatureCount(null); i++)
                {
                    feature      = featureClass.GetFeature(i);
                    clipGeometry = feature.Shape;
                    clipRaster.Add(clipGeometry);
                }
                //将这个过滤器作用于栅格图像
                IPixelOperation pixelOp = (IPixelOperation)m_raster;
                pixelOp.PixelFilter = (IPixelFilter)clipRaster;

                //如果输入的栅格中并不包含NoData和曾经使用过的最大像素深度,则输出文件的像素深度和NoData赋值
                IRasterProps rasterProps = (IRasterProps)m_raster;
                rasterProps.NoDataValue = 0;
                rasterProps.PixelType   = rstPixelType.PT_USHORT;
                //存储剪裁结果栅格图像
                IWorkspace rstWs = wsf.OpenFromFile(@"D:\RDB", 0);
                //保存输出
                ISaveAs saveas = (ISaveAs)m_raster;
                saveas.SaveAs("clip_result.tif", rstWs, "TIFF");
            }
            catch (System.Exception ex)//捕获异常,输出异常信息
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        static void Main()
        {
            #region Initialize license
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null;
            try
            {
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic);
                Console.WriteLine("License Checkout successful.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
            }
            #endregion
            try
            {
                //Get the location for data installed with .net sdk
                string          versionInfo  = RuntimeManager.ActiveRuntime.Version;
                RegistryKey     regKey       = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ESRI\ArcObjectsSDK" + versionInfo + @"\.NET");
                string          path         = System.Convert.ToString(regKey.GetValue("MainDir"));
                string          rasterFolder = System.IO.Path.Combine(path, @"Samples\ArcObjectsNET\CustomNodataFilter");
                IPixelOperation raster       = (IPixelOperation)OpenRasterDataset(rasterFolder, "testimage.tif");

                if (raster == null)
                {
                    Console.WriteLine("invalid raster");
                    return;
                }

                //create nodatafilter and set properties
                CustomNodataFilter.INodataFilter nFilter = new CustomNodataFilter.NodataFilter();

                //filter out all values between 0 and 50 as nodata
                nFilter.MinNodataValue = 0;
                nFilter.MaxNodataValue = 50;

                //apply the convolutionfilter to raster
                raster.PixelFilter = nFilter;

                //set nodata value using the minimum of the nodata range
                IRasterProps rasterProps = (IRasterProps)raster;
                rasterProps.NoDataValue = 0;

                //save the filtered raster to a new raster dataset in TEMP directory
                ISaveAs saveAs = (ISaveAs)raster;
                //IWorkspace workspace = OpenWorkspace(Environment.GetEnvironmentVariable("TEMP"));
                IWorkspace workspace = OpenWorkspace(rasterFolder);
                saveAs.SaveAs("nodata.tif", workspace, "TIFF");

                Console.WriteLine("Completed");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDown()
            aoInit.Shutdown();
        }
Пример #29
0
        /// <summary>
        /// Runs the selected density operations on the input feature class.
        /// </summary>
        /// <param name="pFC"></param>
        /// <returns></returns>
        private IRaster Density(IFeatureClass pFC)
        {
            IRaster pRaster = null;

            try
            {
                IDensityOp pDensityOp = new RasterDensityOpClass();

                //create a feature class descriptor to specify a field
                IFeatureClassDescriptor pFCD = new FeatureClassDescriptorClass();
                if (m_sField != "None")
                {
                    pFCD.Create(pFC, null, m_sField);
                }
                else
                {
                    pFCD.Create(pFC, null, null);
                }


                //run the density op
                //set the output resolution

                //make sure this scale factor is always in right units.
                object oScaleFactor = 1;
                switch (m_sDensityUnits + m_sMapUnits)
                {
                case "per square km" + "Meter":
                    oScaleFactor = 1000;
                    break;

                case "per square mile" + "Meter":
                    oScaleFactor = 1609.344;
                    break;

                case "per square mile" + "Foot_US":
                case "per square mile" + "Foot":
                    oScaleFactor = 5280;
                    break;

                case "per square km" + "Foot_US":
                case "per square km" + "Foot":
                    oScaleFactor = 3280.84;
                    break;

                case "per square nm" + "Meter":
                    oScaleFactor = 1852;
                    break;

                case "per square nm" + "Foot_US":
                case "per square nm" + "Foot":
                    oScaleFactor = 6076.12;
                    break;
                }

                object oRadius = m_dRadius;

                IGeoDataset pOutRaster = null;

                if (m_sDensityType == "Kernel")
                {
                    pOutRaster = pDensityOp.KernelDensity((IGeoDataset)pFCD, ref oRadius, ref oScaleFactor);
                }
                else
                {
                    esriGeometryType thisType = pFC.ShapeType;
                    if (thisType == esriGeometryType.esriGeometryPolyline)
                    {
                        pOutRaster = pDensityOp.LineDensity((IGeoDataset)pFCD, ref oRadius, ref oScaleFactor);
                    }
                    else if (thisType == esriGeometryType.esriGeometryPoint)
                    {
                        IRasterNeighborhood pNbr = new RasterNeighborhoodClass();

                        if (m_sRadiusType == "Cells")
                        {
                            pNbr.SetCircle(m_dRadius, esriGeoAnalysisUnitsEnum.esriUnitsCells);
                        }
                        else
                        {
                            pNbr.SetCircle(m_dRadius, esriGeoAnalysisUnitsEnum.esriUnitsMap);
                        }

                        pOutRaster = pDensityOp.PointDensity((IGeoDataset)pFCD, pNbr, ref oScaleFactor); //ref oCellSize);
                    }
                }
                pRaster = (IRaster)pOutRaster;

                //check output spatial reference
                IRasterProps pRProps = (IRasterProps)pRaster;
                pRProps.SpatialReference = m_pLayerSR;


                //save the raster to disk
                IWorkspace pOutWS  = clsStatic.OpenWorkspace(m_sOutPath);
                ISaveAs    pSaveAs = (ISaveAs)pRaster;
                if (pSaveAs.CanSaveAs("GRID") == true)
                {
                    pSaveAs.SaveAs(pFC.AliasName + "_" + m_sOutName, pOutWS, "GRID");
                }

                IMap pMap = ArcMap.Document.FocusMap;

                //calculate raster stats
                IRasterDataset pRDS = clsStatic.OpenRasterDataset(m_sOutPath, pFC.AliasName + "_" + m_sOutName);
                CalcStats(pRDS);

                //add the layer to the map
                IRasterLayer pRL   = clsStatic.RasterDataset2RasterLayer(m_sOutPath, pFC.AliasName + "_" + m_sOutName, false, pMap);
                IRgbColor    pRGB1 = new RgbColorClass();
                IRgbColor    pRGB2 = new RgbColorClass();
                pRGB2.Blue  = 0;
                pRGB2.Green = 0;
                pRGB2.Red   = 255;
                pRGB1.Blue  = 255;
                pRGB1.Green = 0;
                pRGB1.Red   = 0;
                //pRL.CreateFromRaster(pRaster);
                CreateRasterStretchRenderer(pRL, pRGB1, pRGB2);

                pMap.AddLayer(pRL);

                return(pRaster);
            }
            catch (Exception ex)
            {
                clsStatic.ShowErrorMessage(ex.ToString());
            }
            return(pRaster);
        }
Пример #30
0
        /// <summary>
        /// 降维
        /// </summary>
        public bool BandReduce(out string msg)
        {
            IRasterDataset    pRasterDataset = null;
            IRaster           pRaster        = null;
            StreamReader      sr             = null;
            IWorkspaceFactory pWKSF          = null;
            IWorkspace        pWorkspace     = null;

            try
            {
                //调用IDL代码降维,存在32位内存不足问题。
                _Hyper_BandReduce = System.IO.Path.Combine(BLL.ConstDef.PATH_TEMP, DateTime.Now.ToFileTime().ToString() + ".tif");
                //string cmd = BLL.ConstDef.IDL_FUN_BANDREDUCE + ",'" + _Hyper + "','" + ConstDef.FILE_BANDS + "','" + _Hyper_BandReduce + "'";
                //BLL.EnviVars.instance.IdlModel.Execute(cmd);
                //BLL.EnviVars.instance.IdlModel.Distroy();
                sr = new StreamReader(ConstDef.FILE_BANDS, Encoding.Default);
                string   strBands = sr.ReadLine();
                string[] bandsArr = strBands.Split(',');
                pRasterDataset = EngineAPI.OpenRasterFile(_Hyper);
                pRaster        = (pRasterDataset as IRasterDataset2).CreateFullRaster();

                IRasterBandCollection pRasterBandCollection = pRaster as IRasterBandCollection;
                foreach (string str in bandsArr)
                {
                    int bandIndex = int.Parse(str) - 1;
                    if (-1 < bandIndex && bandIndex < pRasterBandCollection.Count)
                    {
                        pRasterBandCollection.Remove(bandIndex);
                    }
                }
                IRasterBand    pBand             = pRasterBandCollection.Item(0);
                IRasterDataset pOutRasterDataset = pBand.RasterDataset;
                ISaveAs        pSaveAs           = pOutRasterDataset as ISaveAs;
                FileInfo       fInfo             = new FileInfo(_Hyper_BandReduce);
                pWKSF      = new RasterWorkspaceFactoryClass();
                pWorkspace = pWKSF.OpenFromFile(fInfo.DirectoryName, 0);
                if (fInfo.Extension == ".img")
                {
                    IDataset pDataset = pSaveAs.SaveAs(fInfo.Name, pWorkspace, "IMAGINE Image");
                    Marshal.ReleaseComObject(pDataset);
                }
                if (fInfo.Extension == ".tif")
                {
                    IDataset pDataset = pSaveAs.SaveAs(fInfo.Name, pWorkspace, "TIFF");
                    Marshal.ReleaseComObject(pDataset);
                }
                Marshal.ReleaseComObject(pSaveAs);
                msg = "";
                return(true);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }
            finally
            {
                if (pWorkspace != null)
                {
                    Marshal.ReleaseComObject(pWorkspace);
                }
                if (pWKSF != null)
                {
                    Marshal.ReleaseComObject(pWKSF);
                }
                if (pRaster != null)
                {
                    Marshal.ReleaseComObject(pRaster);
                }
                sr.Close();
                sr.Dispose();
            }
        }