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); }
/// <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); }
/// <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); }
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); } }
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; }
//保存分析结果 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); }
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); }
void UpdateSaveAs() { bool isSavable = false; ISaveAs saveAs = source.Provider as ISaveAs; if (saveAs != null) { isSavable = saveAs.IsSavableAs; } WriteControl(ControlFlag.SaveAsButton | ControlFlag.Enabled, isSavable); }
/// <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"); }
/// <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); }
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); } }
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()); } }
/// <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); } } }
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(); }
/// <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); }
/// <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 }
/// <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(); } }
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(); }
/// <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); } } }
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); } } }