/// <summary> /// 转换 /// </summary> /// <param name="pFeatureClass">要素类</param> /// <param name="fieldName">栅格采用的字段</param> /// <param name="rasterWorkSpace">输出栅格的工作空间</param> /// <param name="newRasterName">新的栅格名称</param> public void Convert(IFeatureClass pFeatureClass, string fieldName, string rasterWorkSpace, string newRasterName) { FileHelper.DeleteFile(rasterWorkSpace, newRasterName, ".tif", ".tfw", ".tif.aux"); IFeatureClassDescriptor featureClassDescriptor = new FeatureClassDescriptorClass(); featureClassDescriptor.Create(pFeatureClass, null, fieldName); IGeoDataset geoDataset = (IGeoDataset)featureClassDescriptor; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(rasterWorkSpace, 0); IConversionOp conversionOp = new RasterConversionOpClass(); IRasterAnalysisEnvironment rasterAnalysisEnvironment = (IRasterAnalysisEnvironment)conversionOp; rasterAnalysisEnvironment.OutWorkspace = workspace; //set cell size rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref _cellSize); //set output extent object objectMissing = Type.Missing; rasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref _extentEnvelope, ref objectMissing); //set output spatial reference rasterAnalysisEnvironment.OutSpatialReference = ((IGeoDataset)pFeatureClass).SpatialReference; //convertion conversionOp.ToRasterDataset(geoDataset, _rasterType, workspace, newRasterName); }
private IInterpolationOp SetRasterInterpolationAnalysisEnv(String rasterpath, double cellsize, IFeatureLayer pFeatLayer) { object Missing = Type.Missing; IWorkspaceFactory pWSF; pWSF = new RasterWorkspaceFactoryClass(); IWorkspace pWorkspace = pWSF.OpenFromFile(rasterpath, 0); IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment pRsEnv = (IRasterAnalysisEnvironment)pInterpolationOp; pRsEnv.OutWorkspace = pWorkspace; //装箱操作 object objCellSize = cellsize; pRsEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref objCellSize); IEnvelope pEnv = new EnvelopeClass(); pEnv.XMin = pFeatLayer.AreaOfInterest.XMin; pEnv.XMax = pFeatLayer.AreaOfInterest.XMax; pEnv.YMin = pFeatLayer.AreaOfInterest.YMin; pEnv.YMax = pFeatLayer.AreaOfInterest.YMax; object objExtent = pEnv; pRsEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref objExtent, ref Missing); return(pInterpolationOp); }
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); }
private IFunctionRasterDataset createBarrierRaster() { IFeatureClassDescriptor ftrDesc = new FeatureClassDescriptorClass(); IQueryFilter qf = new QueryFilterClass(); ftrDesc.Create(BarriersFeatureClass, qf, BarriersFeatureClass.OIDFieldName); IConversionOp convOp = new RasterConversionOpClass(); IRasterAnalysisEnvironment rasterAnalysisEnvironment = (IRasterAnalysisEnvironment)convOp; IRasterAnalysisGlobalEnvironment rasterAnalysisGlobalEnvironment = (IRasterAnalysisGlobalEnvironment)convOp; rasterAnalysisGlobalEnvironment.AvoidDataConversion = true; rasterAnalysisEnvironment.OutSpatialReference = sp; rasterAnalysisEnvironment.OutWorkspace = OutWorkspace; //object cells = Dem.RasterInfo.CellSize; object ext = ((IGeoDataset)Dem).Extent; object snap = ((IGeoDataset)Dem); rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, Dem); rasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ext, Dem); string outRdName = rsUtil.getSafeOutputName(OutWorkspace, "sBarrier"); IRasterDataset geoDset = convOp.ToRasterDataset((IGeoDataset)ftrDesc, "GRID", OutWorkspace, outRdName); IGeoDatasetSchemaEdit2 geoSch = (IGeoDatasetSchemaEdit2)geoDset; if (geoSch.CanAlterSpatialReference) { geoSch.AlterSpatialReference(rasterAnalysisEnvironment.OutSpatialReference); } return(rsUtil.createIdentityRaster(geoDset)); }
public IGeoDataset GetIDW(IFeatureClass _pFeatureClass, string _pFieldName, double _pDistance, double _pCell, int _pPower) { IGeoDataset Geo = _pFeatureClass as IGeoDataset; object pExtent = Geo.Extent; object o = Type.Missing; IFeatureClassDescriptor pFeatureClassDes = new FeatureClassDescriptorClass(); pFeatureClassDes.Create(_pFeatureClass, null, _pFieldName); IInterpolationOp pInterOp = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment pRasterAEnv = pInterOp as IRasterAnalysisEnvironment; // pRasterAEnv.Mask = Geo; pRasterAEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref pExtent, ref o); object pCellSize = _pCell;//可以根据不同的点图层进行设置 pRasterAEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref pCellSize); IRasterRadius pRasterrad = new RasterRadiusClass(); object obj = Type.Missing; // pRasterrad.SetFixed(_pDistance, ref obj); pRasterrad.SetVariable(12); object pBar = Type.Missing; IGeoDataset pGeoIDW = pInterOp.IDW(pFeatureClassDes as IGeoDataset, _pPower, pRasterrad, ref pBar); return(pGeoIDW); }
public static void Mlayer_IDW_Click() { // 用反距离IDW插值生成的栅格图像。如下: IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass(); IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); string pPath = Application.StartupPath + @"\MakeContours\Cont.shp"; string pFolder = System.IO.Path.GetDirectoryName(pPath); string pFileName = System.IO.Path.GetFileName(pPath); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFolder, 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass oFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName); IFeatureClassDescriptor pFCDescriptor = new FeatureClassDescriptorClass(); pFCDescriptor.Create(oFeatureClass, null, "shape.z"); IRasterRadius pRadius = new RasterRadiusClass(); object objectMaxDistance = null; object objectbarrier = null; object missing = Type.Missing; pRadius.SetVariable(12, ref objectMaxDistance); object dCellSize = 1; object snapRasterData = Type.Missing; IEnvelope pExtent; pExtent = new EnvelopeClass(); Double xmin = 27202; Double xmax = 31550; Double ymin = 19104; Double ymax = 22947; pExtent.PutCoords(xmin, ymin, xmax, ymax); object extentProvider = pExtent; IRasterAnalysisEnvironment pEnv = pInterpolationOp as IRasterAnalysisEnvironment; pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCellSize); pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData); IGeoDataset poutGeoDataset = pInterpolationOp.IDW((IGeoDataset)pFCDescriptor, 2, pRadius, ref objectbarrier); ISurfaceOp surOp = new RasterSurfaceOpClass(); IRaster pOutRaster = poutGeoDataset as IRaster; IRasterLayer pOutRasLayer = new RasterLayer(); pOutRasLayer.CreateFromRaster(pOutRaster); IMap pMap = Common.DataEditCommon.g_pMap; pMap.AddLayer(pOutRasLayer); Common.DataEditCommon.g_axTocControl.Refresh(); Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh(); }
public static void Mlayer_Krige_Click() { // 用克里金Krige插值生成的栅格图像。如下: IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); string pPath = Application.StartupPath + @"\MakeContours\Cont.shp"; string pFolder = System.IO.Path.GetDirectoryName(pPath); string pFileName = System.IO.Path.GetFileName(pPath); IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pFolder, 0); IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace; IFeatureClass oFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName); IFeatureClassDescriptor pFCDescriptor = new FeatureClassDescriptorClass(); pFCDescriptor.Create(oFeatureClass, null, "shape.z"); IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment pEnv = pInterpolationOp as IRasterAnalysisEnvironment; object Cellsize = 0.004;//Cell size for output raster;0.004 pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref Cellsize); //设置输出范围 //27202 19104;27202 22947;31550 22947;31550 19104 object snapRasterData = Type.Missing; IEnvelope pExtent; pExtent = new EnvelopeClass(); Double xmin = 27202; Double xmax = 31550; Double ymin = 19104; Double ymax = 22947; pExtent.PutCoords(xmin, ymin, xmax, ymax); object extentProvider = pExtent; pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData); Double dSearchD = 10; object pSearchCount = 3; object missing = Type.Missing; IRasterRadius pRadius = new RasterRadius(); pRadius.SetFixed(dSearchD, ref pSearchCount); //pRadius.SetVariable((int)pSearchCount, ref dSearchD); IGeoDataset poutGeoDataset = pInterpolationOp.Krige((IGeoDataset)pFCDescriptor, esriGeoAnalysisSemiVariogramEnum.esriGeoAnalysisGaussianSemiVariogram, pRadius, false, ref missing); IRaster pOutRaster = poutGeoDataset as IRaster; IRasterLayer pOutRasLayer = new RasterLayer(); pOutRasLayer.CreateFromRaster(pOutRaster); IMap pMap = Common.DataEditCommon.g_pMap; pMap.AddLayer(pOutRasLayer); Common.DataEditCommon.g_axTocControl.Refresh(); Common.DataEditCommon.g_pAxMapControl.ActiveView.Refresh(); }
/// <summary> /// Sets the output environment for this raster tool, using the specified extent for output. /// </summary> /// <param name="pRasterTool">The tool to set the ouput environment for.</param> /// <param name="sSubDir">The subdirectory to use for output.</param> /// <param name="extentProvider">An IEnvelope or RasterDataset that defines the output extent.</param> /// <remarks>The extentProvider determines the extent, but the default raster (the input DEM) determines cell size /// and snap registration of the cells.</remarks> internal void SetAnalysisEnvironment(IRasterAnalysisEnvironment rasterTool, object extentProvider) { object inputGrid = _GetDefaultGrid(); rasterTool.DefaultOutputRasterPrefix = "UrbDelTmp"; rasterTool.OutWorkspace = GetTempRasterWorkspace(); rasterTool.OutSpatialReference = ((IGeoDataset)inputGrid).SpatialReference; rasterTool.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref inputGrid); rasterTool.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref inputGrid); }
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); } }
/// <summary> /// 设置栅格分析环境 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="analysisOperation"></param> /// <param name="referencedRaster"></param> /// <param name="cellSize"></param> public static void SetAnalysisEnvironment <T>(T analysisOperation, IRaster referencedRaster, object cellSize) where T : IMapAlgebraOp { IRasterAnalysisEnvironment pRasAnalysisEnvironment = (IRasterAnalysisEnvironment)analysisOperation; //设置输出空间 SetRasterAnalysisOutWorkspace(pRasAnalysisEnvironment); //设置输出参考栅格 IRasterProps rasterProps = (IRasterProps)referencedRaster; //装箱操作,必须设置,因为输入栅格可能空间参考等属性不同 //设置输出数据像元大小 pRasAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSize); //设置栅格分析处理范围 object objExtent = rasterProps.Extent; pRasAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref objExtent); //设置输出数据空间参考 SetOutSpatialReference(referencedRaster, pRasAnalysisEnvironment); }
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 IRaster RasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo) { if (clipGeo == null) { return(null); } IRaster clipRaster = null; 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); 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; } return(clipRaster); }
public void RasterMeaAtt(IRaster pRaster, IGeometry pGeoMetry, ref double pixelmax, ref double pixelmin) { IPolygon clipGeo = pGeoMetry as IPolygon; 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 = null; //裁切后得到的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; } CalRasterAtt(clipRaster as IRaster2, ref pixelmax, ref pixelmin); }
private void button_IDW_TIME_Click(object sender, EventArgs e) { object obj = null; ILayer pLayer = new FeatureLayerClass(); IFeatureClass featureClass = GetFeatureClass(@"D:\a_gis工程设计实践课\china\墓穴地shp\grave.shp"); IGeoDataset geo = featureClass as IGeoDataset; object extend = geo.Extent; object o = null; IFeatureClassDescriptor feades = new FeatureClassDescriptorClass(); feades.Create(featureClass, null, "time_inter"); IRasterRadius rasterrad = new RasterRadiusClass(); rasterrad.SetVariable(12, ref obj); object dCell = 0.014800000;//可以根据不同的点图层进行设置 IInterpolationOp interpla = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment rasanaenv = interpla as IRasterAnalysisEnvironment; rasanaenv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell); rasanaenv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o); IGeoDataset g_GeoDS_Raster = interpla.IDW((IGeoDataset)feades, 2, rasterrad, ref obj); IRaster pOutRsater = (IRaster)g_GeoDS_Raster; IRasterLayer pOutRasterlayer = new RasterLayerClass(); pOutRasterlayer.CreateFromRaster(pOutRsater); pOutRasterlayer.Name = "时间久远程度"; PixelValue2 = Class_GetPixelValue(pOutRasterlayer); IRasterClassifyColorRampRenderer pRClassRend = new RasterClassifyColorRampRendererClass(); IRasterRenderer pRRend = pRClassRend as IRasterRenderer; IRaster pRaster = pOutRasterlayer.Raster; IRasterBandCollection pRBandCol = pRaster as IRasterBandCollection; IRasterBand pRBand = pRBandCol.Item(0); if (pRBand.Histogram == null) { pRBand.ComputeStatsAndHist(); } pRRend.Raster = pRaster; pRClassRend.ClassCount = 10; pRRend.Update(); IRgbColor pFromColor = new RgbColorClass(); pFromColor.Red = 135;//天蓝色 pFromColor.Green = 206; pFromColor.Blue = 235; IRgbColor pToColor = new RgbColorClass(); pToColor.Red = 124;//草坪绿 pToColor.Green = 252; pToColor.Blue = 0; IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass(); colorRamp.Size = 10; colorRamp.FromColor = pFromColor; colorRamp.ToColor = pToColor; bool createColorRamp; colorRamp.CreateRamp(out createColorRamp); IFillSymbol fillSymbol = new SimpleFillSymbolClass(); for (int i = 0; i < pRClassRend.ClassCount; i++) { fillSymbol.Color = colorRamp.get_Color(i); pRClassRend.set_Symbol(i, fillSymbol as ISymbol); pRClassRend.set_Label(i, pRClassRend.get_Break(i).ToString("0.00")); } pOutRasterlayer.Renderer = pRRend; this.axMapControl1.AddLayer(pOutRasterlayer); //两种方法的结合后 }
/// <summary> /// 执行地图代数运算 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks></remarks> private void Button_OK_Click(System.Object sender, System.EventArgs e) { IRasterLayer pRasLayer = default(IRasterLayer); IRaster pRaster = default(IRaster); IEnvelope layExtend = default(IEnvelope); double AnalysisExtentLeft = 0; double AnalysisExtentRight = 0; double AnalysisExtentTop = 0; double AnalysisExtentBottom = 0; string layerNameFir = null; try { if (LayerList.Count != 0) { if (textBox_Result.Text.ToString().Length != 0) { layerNameFir = LayerList[0].ToString(); layExtend = GetLayerExtend(layerNameFir); AnalysisExtentLeft = layExtend.XMin; AnalysisExtentRight = layExtend.XMax; AnalysisExtentTop = layExtend.YMax; AnalysisExtentBottom = layExtend.YMin; pMapAlgebraOp = new RasterMapAlgebraOp() as IMapAlgebraOp; //设置栅格计算分析环境 IRasterAnalysisEnvironment pRasAnaEnv = default(IRasterAnalysisEnvironment); pRasAnaEnv = (IRasterAnalysisEnvironment)pMapAlgebraOp; pRasAnaEnv.VerifyType = esriRasterVerifyEnum.esriRasterVerifyOn; object dddd; dddd = GetRasterCellSize(layerNameFir); pRasAnaEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dddd); //设置分析范围pAnaExtent IEnvelope pAnaExtent = default(IEnvelope); pAnaExtent = new Envelope() as IEnvelope; pAnaExtent.XMin = Convert.ToDouble(AnalysisExtentLeft); pAnaExtent.XMax = Convert.ToDouble(AnalysisExtentRight); pAnaExtent.YMax = Convert.ToDouble(AnalysisExtentTop); pAnaExtent.YMin = Convert.ToDouble(AnalysisExtentBottom); object dd1 = pAnaExtent; object dd2 = null; pRasAnaEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dd1, ref dd2); foreach (string LayerName in LayerList) { pRasLayer = (IRasterLayer)FindLayerByName(pCurMap, LayerName); //MsgBox(LayerName) pRaster = pRasLayer.Raster; RasterList.Add(pRaster); } //将容量设置为 ArrayList 中元素的实际数目 LayerList.TrimToSize(); RasterList.TrimToSize(); //绑定 int i = 0; if (LayerList.Count == RasterList.Count) { for (i = 0; i <= LayerList.Count - 1; i++) { pMapAlgebraOp.BindRaster((IGeoDataset)RasterList[i], LayerList[i].ToString()); } } //获取文本框中的运算表达式() string sCalExpression = null; sCalExpression = textBox_Calculate.Text; //执行地图代数运算 IRaster pOutRasterDS = default(IRaster); pOutRasterDS = (IRaster)pMapAlgebraOp.Execute(sCalExpression); //解除绑定 if (LayerList.Count == RasterList.Count) { for (i = 0; i <= LayerList.Count - 1; i++) { pMapAlgebraOp.UnbindRaster(LayerList[i].ToString()); } } //保存到工作空间 IWorkspaceFactory pWsFact = default(IWorkspaceFactory); IWorkspace pWS = default(IWorkspace); int hwnd = 0; pWsFact = new RasterWorkspaceFactory(); pWS = pWsFact.OpenFromFile(sOutRasPath, hwnd); IRasterBandCollection pRasterbandCollection = default(IRasterBandCollection); pRasterbandCollection = (IRasterBandCollection)pOutRasterDS; IDataset pDataset = default(IDataset); pDataset = pRasterbandCollection.SaveAs(sOutRasName, pWS, "IMAGINE Image"); //输出到mapcontrol中 IRasterDataset pOutResultDS = default(IRasterDataset); pOutResultDS = (IRasterDataset)pDataset; IRasterLayer pOutRasterLayer = default(IRasterLayer); pOutRasterLayer = new RasterLayer(); pOutRasterLayer.CreateFromDataset(pOutResultDS); //MapControlMain.AddLayer(pOutRasterLayer) pCurMap.AddLayer(pOutRasterLayer); this.Close(); } else { MessageBox.Show("保存计算结果为空,请输入结果文件名!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); //Interaction.MsgBox(ex.ToString); } }
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); } }
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); } }
private void buildPathAllocation() { IDistanceOp2 dOp = new RasterDistanceOpClass(); IRasterAnalysisEnvironment rasterAnalysisEnvironment = (ESRI.ArcGIS.GeoAnalyst.IRasterAnalysisEnvironment)dOp; rasterAnalysisEnvironment.OutSpatialReference = ((IGeoDataset)Dem).SpatialReference; rasterAnalysisEnvironment.OutWorkspace = OutWorkspace; object ext = ((IGeoDataset)RoadFeatureClass).Extent; object snap = ((IGeoDataset)Dem); rasterAnalysisEnvironment.SetCellSize(ESRI.ArcGIS.GeoAnalyst.esriRasterEnvSettingEnum.esriRasterEnvValue, Dem); rasterAnalysisEnvironment.SetExtent(ESRI.ArcGIS.GeoAnalyst.esriRasterEnvSettingEnum.esriRasterEnvValue, ext, Dem); IRasterAnalysisGlobalEnvironment analysisGlobalEnv = (IRasterAnalysisGlobalEnvironment)dOp; analysisGlobalEnv.AvoidDataConversion = true; IRasterOpBase rasOpBase = (IRasterOpBase)dOp; IRasterDatasetName rasDatasetName; rasDatasetName = new RasterDatasetNameClass(); IDatasetName datasetName; datasetName = (IDatasetName)rasDatasetName; datasetName.WorkspaceName = (IWorkspaceName)((IDataset)OutWorkspace).FullName; string onRoadNm = rsUtil.getSafeOutputName(OutWorkspace, "onRoadHr"); datasetName.Name = onRoadNm; rasOpBase.AddOutputDatasetName(0, datasetName); object noVl = Type.Missing; IFunctionRasterDataset cr1 = rsUtil.calcArithmaticFunction(RoadRaster, speedConFactor, esriRasterArithmeticOperation.esriRasterMultiply); IFunctionRasterDataset costRs = rsUtil.calcArithmaticFunction(1, cr1, esriRasterArithmeticOperation.esriRasterDivide); IGeoDataset rpdOut = dOp.PathDistance((IGeoDataset)FacilityFeatureClass, costRs, Dem, noVl, noVl, noVl, noVl, noVl, noVl);//outputs in hours FunctionAccumulatedPathDistance = rsUtil.createIdentityRaster((IRaster)rpdOut); // Use FunctonAccumulated Path Distance (hours) for allocation string frRoadDist = rsUtil.getSafeOutputName(OutWorkspace, "offRoadHr"); datasetName.Name = frRoadDist; string frRoadAllo = rsUtil.getSafeOutputName(OutWorkspace, "onRoadAllo"); IRasterDatasetName rasDatasetName2 = new RasterDatasetNameClass(); IDatasetName datasetName2 = (IDatasetName)rasDatasetName2; datasetName2.WorkspaceName = (IWorkspaceName)((IDataset)OutWorkspace).FullName; datasetName2.Name = frRoadAllo; string frRoadBack = rsUtil.getSafeOutputName(OutWorkspace, "offRoadBack"); IRasterDatasetName rasDatasetName3 = new RasterDatasetNameClass(); IDatasetName datasetName3 = (IDatasetName)rasDatasetName3; datasetName3.WorkspaceName = (IWorkspaceName)((IDataset)OutWorkspace).FullName; datasetName3.Name = frRoadBack; rasOpBase.AddOutputDatasetName(0, datasetName); rasOpBase.AddOutputDatasetName(1, datasetName3); rasOpBase.AddOutputDatasetName(2, datasetName2); IFunctionRasterDataset costRS = null; //add in barriers to costRS if (OffRoadSpeedRaster != null) { IFunctionRasterDataset c1 = rsUtil.calcArithmaticFunction(OffRoadSpeedRaster, speedConFactor, esriRasterArithmeticOperation.esriRasterMultiply); costRS = rsUtil.calcArithmaticFunction(1, c1, esriRasterArithmeticOperation.esriRasterDivide); } else { costRS = rsUtil.constantRasterFunction(FunctionAccumulatedPathDistance, 1 / (OffRoadSpeed * speedConFactor)); } //add in barriers to costRs IFunctionRasterDataset rdCs = null;//rsUtil.calcArithmaticFunction(FunctionAccumulatedPathDistance, 1000, esriRasterArithmeticOperation.esriRasterMultiply, rstPixelType.PT_LONG); if (BarriersFeatureClass != null) { IFunctionRasterDataset[] rslt = addBarrierRasters(costRS, FunctionAccumulatedPathDistance); costRS = rslt[0]; rdCs = rslt[1]; } else { rdCs = rsUtil.calcArithmaticFunction(FunctionAccumulatedPathDistance, 1000, esriRasterArithmeticOperation.esriRasterMultiply, rstPixelType.PT_LONG); } IGeoDataset rpdOut2 = dOp.PathDistanceFull((IGeoDataset)rdCs, true, false, true, costRS, Dem, noVl, noVl, noVl, noVl, noVl, rdCs); IRasterBandCollection rsbc = (IRasterBandCollection)rpdOut; FunctionAccumulatedFromPathDistance = rsUtil.getBand((IRaster)rpdOut2, 0); FunctionAccumulatedPathAllocation = rsUtil.getBand((IRaster)rpdOut2, 1); }
public void CreateRasterFromPoints(IMap pMap, IFeatureLayer pp, String Path, String Name, String Field) { //1.将Shape文件读取成FeatureClass //2.根据FeatureClass生成IFeatureClassDescriptor //3.创建IRasterRaduis 对象 //设置Cell //4.插值并生成表面 object obj = null; IWorkspaceFactory pShapSpace; pShapSpace = new ShapefileWorkspaceFactory(); IWorkspace pW; pW = pShapSpace.OpenFromFile(Path, 0); IFeatureWorkspace pFeatureWork; pFeatureWork = pW as IFeatureWorkspace; IFeatureClass pFeatureClass = pFeatureWork.OpenFeatureClass("Name"); IGeoDataset Geo = pFeatureClass as IGeoDataset; object extend = Geo.Extent; object o = null; IFeatureClassDescriptor pFeatureClassDes = new FeatureClassDescriptorClass(); pFeatureClassDes.Create(pFeatureClass, null, Field); IRasterRadius pRasterrad = new RasterRadiusClass(); pRasterrad.SetVariable(10, ref obj); object dCell = 0.5;//可以根据不同的点图层进行设置 IInterpolationOp Pinterpla = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment pRasterAnaEn = Pinterpla as IRasterAnalysisEnvironment; pRasterAnaEn.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell); pRasterAnaEn.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o); IGeoDataset pGRaster; object hh = 3; pGRaster = Pinterpla.IDW((IGeoDataset)pFeatureClassDes, 2, pRasterrad, ref hh); ISurfaceOp pSurF; pSurF = new RasterSurfaceOpClass(); IGeoDataset pCour; object o1 = 0; pCour = pSurF.Contour(pGRaster, 5, ref o1); IFeatureLayer pLa; pLa = new FeatureLayerClass(); IFeatureClass pClass = pCour as IFeatureClass; pLa.FeatureClass = pClass; pLa.Name = pClass.AliasName; pMap.AddLayer(pLa as ILayer); }
/// <summary> /// return operation watershed handler /// </summary> /// <param name="boundVariables">>bound Variables</param> /// <param name="operationInput">operation Input</param> /// <param name="outputFormat">output Format</param> /// <param name="requestProperties">request Properties</param> /// <param name="responseProperties">response Properties</param> /// <returns>operation watershed handler</returns> private byte[] OperationWatershedHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; long?idWatershed; if (operationInput.Exists("idWatershed")) { if (!operationInput.TryGetAsLong("idWatershed", out idWatershed)) { throw new ArgumentNullException("idWatershed"); } } else { idWatershed = 0; } JsonObject jsonObjectPoint; if (!operationInput.TryGetJsonObject("location", out jsonObjectPoint)) { throw new ArgumentNullException("location"); } IPoint location = Conversion.ToGeometry(jsonObjectPoint, esriGeometryType.esriGeometryPoint) as IPoint; if (location == null) { throw new ArgumentException("Invalid location", "location"); } double?snapDistance; if (!operationInput.TryGetAsDouble("snapDistance", out snapDistance)) { throw new ArgumentNullException("snapDistance"); } snapDistance = snapDistance ?? 0.0; long?idAccumulation; if (!operationInput.TryGetAsLong("idAccumulation", out idAccumulation) || !idAccumulation.HasValue) { throw new ArgumentNullException("idAccumulation"); } long?idDirection; if (!operationInput.TryGetAsLong("idDirection", out idDirection) || !idDirection.HasValue) { throw new ArgumentNullException("idDirection"); } string methodName = MethodBase.GetCurrentMethod().Name; try { IFeatureWorkspace featureWorkspace = Helper.CreateInMemoryWorkspace() as IFeatureWorkspace; IFeatureClass featureClass = this.CreateFeatureClass(location, featureWorkspace); IFeature feature = featureClass.CreateFeature(); feature.Shape = location; feature.set_Value(featureClass.FindField(SAUtility.FieldNameIdWatershed), (int)idWatershed.Value); feature.Store(); IHydrologyOp hydrologyOp = new RasterHydrologyOp() as IHydrologyOp; IGeoDataset accumulation = this.GetGeodataset((int)idAccumulation.Value); IGeoDataset direction = this.GetGeodataset((int)idDirection.Value); IFeatureClassDescriptor featureClassDescriptor = new FeatureClassDescriptorClass(); featureClassDescriptor.Create(featureClass, null, SAUtility.FieldNameIdWatershed); IGeoDataset pourPoint = featureClassDescriptor as IGeoDataset; IRasterAnalysisEnvironment rasterAnalysisEnvironment = hydrologyOp as IRasterAnalysisEnvironment; object extentProvider = Type.Missing; object snapRasterData = Type.Missing; rasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvMaxOf, ref extentProvider, ref snapRasterData); IGeoDataset snapRaster = hydrologyOp.SnapPourPoint(pourPoint, accumulation, snapDistance.Value); IGeoDataset watershed = hydrologyOp.Watershed(direction, snapRaster); IConversionOp conversionOp = new RasterConversionOpClass() as IConversionOp; IGeoDataset featureClassWatershed = conversionOp.RasterDataToPolygonFeatureData(watershed, featureWorkspace as IWorkspace, "WatershedPolygon", true); IRecordSetInit recordset = new RecordSetClass(); recordset.SetSourceTable(featureClassWatershed as ITable, null); byte[] recorset = Conversion.ToJson(recordset as IRecordSet); this.logger.LogMessage(ServerLogger.msgType.infoDetailed, methodName, SAUtility.MessageCodeSOE, string.Format("Watershed created with success. IdWatershed {0}", (int)idWatershed.Value)); return(recorset); } catch (Exception ex) { this.logger.LogMessage(ServerLogger.msgType.error, methodName, SAUtility.MessageCodeSOE, ex.Message); return(new ObjectError("Error create watershed: see log ags").ToJsonObject().JsonByte()); } }
public bool SetRegionToNoDataValue() { try { if (m_pSrcRaster == null || m_pClipPolygon == null || double.IsNaN(m_dbNoDataValue)) { return(false); } IGeoDataset pSrcGeoDataset = m_pSrcRaster as IGeoDataset; IExtractionOp pRasterExtractionOp = new RasterExtractionOpClass(); IRasterProps pSrcRasterProps = m_pSrcRaster as IRasterProps; double dbCellSize = (pSrcRasterProps.MeanCellSize().X + pSrcRasterProps.MeanCellSize().Y) / 2; //设置范围和分辨率 IRasterAnalysisEnvironment pRasterAnalysisEnv = pRasterExtractionOp as IRasterAnalysisEnvironment; pRasterAnalysisEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSize); pRasterAnalysisEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, m_pClipPolygon.Envelope, Type.Missing); //pRasterAnalysisEnv.OutSpatialReference = (m_pSrcRaster as IRasterProps).SpatialReference; //保留区域外的值,区域内的设置为原始栅格的无效值 IGeoDataset pDstGeoDataset = pRasterExtractionOp.Rectangle(pSrcGeoDataset, m_pClipPolygon.Envelope, true); //逐点判断像素是否在区域内,在区域内则改变为设置值,否则不变 IRelationalOperator pRelationalOp = m_pClipPolygon as IRelationalOperator; if (pDstGeoDataset is IRaster) { //得到原始栅格的对象,用于修改 IRaster2 pSrcRaster2 = m_pSrcRaster as IRaster2; IRasterDataset2 pSrcRasterDataset2 = pSrcRaster2.RasterDataset as IRasterDataset2; IRaster pTmpRaster = pSrcRasterDataset2.CreateFullRaster(); IRasterEdit pSrcEdit = pTmpRaster as IRasterEdit; //得到图层NoDataValue IRasterProps rasterProps = pSrcRaster2 as IRasterProps; double noData = ClsGDBDataCommon.getNoDataValue(rasterProps.NoDataValue); //得到输出的栅格 IRaster2 pDstRaster2 = pDstGeoDataset as IRaster2; IRasterProps pDstRasterProps = pDstRaster2 as IRasterProps; IRasterCursor pDstRasterCursor = pDstRaster2.CreateCursorEx(null); //pDstRasterCursor.Reset(); do { //得到当前处理的块 IPixelBlock3 pixelBlock3 = pDstRasterCursor.PixelBlock as IPixelBlock3; int nWidth = pixelBlock3.Width; int nHeight = pixelBlock3.Height; IPnt ptLeftTop = pDstRasterCursor.TopLeft; //block值转数组时,NoData转换时有时为NoData,有时为栅格中的最小值 System.Array array = pixelBlock3.get_PixelData(0) as System.Array; //逐点判断: 判断像素是否在区域内,在区域内则改变为设置值,否则不变 for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { double dbX = double.NaN, dbY = double.NaN; //得到当前像素点的地图坐标 int nCurrentX = Convert.ToInt32(ptLeftTop.X + i); int nCurrentY = Convert.ToInt32(ptLeftTop.Y + j); pDstRaster2.PixelToMap(nCurrentX, nCurrentY, out dbX, out dbY); IPoint ptInMap = new PointClass(); ptInMap.X = dbX; ptInMap.Y = dbY; //判断是否在区域内 bool bFlag = pRelationalOp.Contains(ptInMap as IGeometry); if (bFlag) //在当前区域内 { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { double v = Convert.ToDouble(array.GetValue(i, j)); if (v == 0 || v < -3.4e15 || v > 3.4e15) //if (v == 0 || Math.Abs(v -noData) <1e18) { int col, row; pSrcRaster2.MapToPixel(dbX, dbY, out col, out row); //表示getpixelvalue为null表示nodata object obj = pSrcRaster2.GetPixelValue(0, col, row); if (obj == null) { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { array.SetValue(obj, i, j); } } } } } pixelBlock3.set_PixelData(0, array); //得到当前区域块在原图中的左上角像素坐标, 直接修改原栅格的数据 int nPixelLeftX = -1, nPixelLeftY = -1; double dbMapLeftTopX = double.NaN, dbMapLeftTopY = double.NaN; pDstRaster2.PixelToMap(Convert.ToInt32(ptLeftTop.X), Convert.ToInt32(ptLeftTop.Y), out dbMapLeftTopX, out dbMapLeftTopY); //得到当前块左上角的地理坐标 pSrcRaster2.MapToPixel(dbMapLeftTopX, dbMapLeftTopY, out nPixelLeftX, out nPixelLeftY); IPnt ptPixelLeftTop = new PntClass(); ptPixelLeftTop.SetCoords(nPixelLeftX, nPixelLeftY); if (pSrcEdit.CanEdit()) { pSrcEdit.Write(ptPixelLeftTop, pixelBlock3 as IPixelBlock); //pSrcEdit.Refresh(); } else { return(false); } } while (pDstRasterCursor.Next() == true); //更新 pSrcEdit.Refresh(); } else { return(false); } return(true); } catch (System.Exception ex) { return(false); } }
private static void ConvertShape2Raster(string string_0, double double_0, string string_1) { string directoryName; ArgumentException exception; string fileNameWithoutExtension; IWorkspace workspace; Exception exception2; IFeatureClass class2; IWorkspace workspace3; try { directoryName = System.IO.Path.GetDirectoryName(string_0); } catch (ArgumentException exception1) { exception = exception1; Console.WriteLine(exception.Message); Console.WriteLine("ConvertShape2Raster - invalid input Shapefile path for {0}", string_0); return; } try { fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(string_0); } catch (ArgumentException exception3) { exception = exception3; Console.WriteLine(exception.Message); Console.WriteLine("ConvertShape2Raster - invalid input Shapefile name for {0}", string_0); return; } IWorkspaceFactory factory = new ShapefileWorkspaceFactory(); try { workspace = factory.OpenFromFile(directoryName, 0); } catch (Exception exception4) { exception2 = exception4; Console.WriteLine("Unable to find and open the shapefile workspace: {0}.", directoryName); Console.WriteLine(exception2.Message); return; } IFeatureWorkspace workspace2 = (IFeatureWorkspace)workspace; try { class2 = workspace2.OpenFeatureClass(fileNameWithoutExtension); } catch (Exception exception5) { exception2 = exception5; Console.WriteLine("Unable to find and open the shapefile: {0}.", fileNameWithoutExtension); Console.WriteLine(exception2.Message); return; } IGeoDataset dataset = (IGeoDataset)class2; IWorkspaceFactory factory2 = new RasterWorkspaceFactory(); try { workspace3 = factory2.OpenFromFile(directoryName, 0); } catch (Exception exception6) { exception2 = exception6; Console.WriteLine("Unable to find and open the raster workspace: {0}.", directoryName); Console.WriteLine(exception2.Message); return; } IConversionOp op = new RasterConversionOp() as IConversionOp; try { IRasterAnalysisEnvironment environment = (IRasterAnalysisEnvironment)op; environment.OutWorkspace = workspace3; object cellSizeProvider = double_0; environment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider); object extent = dataset.Extent; object snapRasterData = 0; environment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extent, ref snapRasterData); } catch (Exception exception7) { exception2 = exception7; Console.WriteLine( "Unable to set either the output workspace, or extent, or cell size for raster dataset"); Console.WriteLine(exception2.Message); return; } op.ToRasterDataset(dataset, "GRID", workspace3, string_1); }
private void btn_2e_Click(object sender, EventArgs e) { ILayer pLayer = new FeatureLayerClass(); IFeatureClass featureClass = GetFeatureClass(@"D:\a_gis工程设计实践课\china\墓穴地shp\grave.shp"); IGeoDataset geo = featureClass as IGeoDataset; object extend = geo.Extent; object o = null; IFeatureClassDescriptor feades = new FeatureClassDescriptorClass(); feades.Create(featureClass, null, "area"); IRasterRadius rasterrad = new RasterRadiusClass(); rasterrad.SetVariable(12, ref o); object dCell = 0.014800000;//可以根据不同的点图层进行设置 IInterpolationOp interpla = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment rasanaenv = interpla as IRasterAnalysisEnvironment; rasanaenv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell); rasanaenv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o); IGeoDataset g_GeoDS_Raster = interpla.IDW((IGeoDataset)feades, 2, rasterrad, ref o); IRaster pOutRsater = (IRaster)g_GeoDS_Raster; IRasterLayer pOutRasterlayer = new RasterLayerClass(); pOutRasterlayer.CreateFromRaster(pOutRsater); pOutRasterlayer.Name = "两个因素都考虑"; //IRaster raster = pOutRasterlayer.Raster; IRaster2 raster2 = (IRaster2)pOutRsater; // 指定像素块大小 IPnt pntBlock = new PntClass(); pntBlock.X = 1280; pntBlock.Y = 1280; //创建一个光标以给定像素块大小 //定义RasterCursor初始化,参数设为null,内部自动设置PixelBlock大小 //IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(null); IRasterCursor rasterCursor = raster2.CreateCursorEx(null); //控制像素块级别的编辑操作 IRasterEdit rasterEdit = raster2 as IRasterEdit; if (rasterEdit.CanEdit()) { //得到一段光栅带 IRasterBandCollection bandCollection = (IRasterBandCollection)pOutRsater; System.Array pixels; IPnt pnt = null; object value; int bandCount = bandCollection.Count; //创建像素块 IPixelBlock3 pixelBlock3 = null; int blockWidth = 0; int blockHeight = 0; double temp = 0; do { pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; blockWidth = pixelBlock3.Width; blockHeight = pixelBlock3.Height; for (int k = 0; k < bandCount; k++) { //指定平面的像素的数组 pixels = (System.Array)pixelBlock3.get_PixelData(k); for (int i = 0; i < blockWidth; i++) { for (int j = 0; j < blockHeight; j++) { //value = pixels.GetValue(i, j); ////if (Convert.ToInt32(value) == 0) //{ //设置像素的颜色值 temp = PixelValue1[i, j] + PixelValue2[i, j]; pixels.SetValue((int)temp, i, j); //} } } pixelBlock3.set_PixelData(k, pixels); } pnt = rasterCursor.TopLeft; rasterEdit.Write(pnt, (IPixelBlock)pixelBlock3); }while (rasterCursor.Next()); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); //渲染 IRasterClassifyColorRampRenderer pRClassRend = new RasterClassifyColorRampRendererClass(); IRasterRenderer pRRend = pRClassRend as IRasterRenderer; IRaster pRaster = pOutRasterlayer.Raster; IRasterBandCollection pRBandCol = pRaster as IRasterBandCollection; IRasterBand pRBand = pRBandCol.Item(0); if (pRBand.Histogram == null) { pRBand.ComputeStatsAndHist(); } pRRend.Raster = pRaster; pRClassRend.ClassCount = 10; pRRend.Update(); IRgbColor pFromColor = new RgbColorClass(); pFromColor.Red = 135;//天蓝色 pFromColor.Green = 206; pFromColor.Blue = 235; IRgbColor pToColor = new RgbColorClass(); pToColor.Red = 124;//草坪绿 pToColor.Green = 252; pToColor.Blue = 0; IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass(); colorRamp.Size = 10; colorRamp.FromColor = pFromColor; colorRamp.ToColor = pToColor; bool createColorRamp; colorRamp.CreateRamp(out createColorRamp); IFillSymbol fillSymbol = new SimpleFillSymbolClass(); for (int i = 0; i < pRClassRend.ClassCount; i++) { fillSymbol.Color = colorRamp.get_Color(i); pRClassRend.set_Symbol(i, fillSymbol as ISymbol); pRClassRend.set_Label(i, pRClassRend.get_Break(i).ToString("0.00")); } pOutRasterlayer.Renderer = pRRend; this.axMapControl1.AddLayer(pOutRasterlayer); } }