public IRaster CreateRasterSlope(IRaster raster) { try { RasterSurfaceOpClass class2 = new RasterSurfaceOpClass(); IGeoDataset geoDataset = raster as IGeoDataset; double zFactor = Convert.ToDouble(textBoxX3.Text); if (zFactor <= 0) { MessageBox.Show("请指定大于0的正数!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(null); } //float zFactor = 1; object o = zFactor; esriGeoAnalysisSlopeEnum geoType = esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees; IGeoDataset pGeoDataset = class2.Slope(geoDataset, geoType, ref o); IRaster pRaster = (IRaster)pGeoDataset; ISaveAs2 pSaveAs = pRaster as ISaveAs2; IDataset pDataset = pSaveAs.SaveAs(m_ResultPath + ".tif", null, "TIFF"); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset); MessageBox.Show("坡度计算完毕!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(pRaster); } catch (SystemException e) { MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } }
public IRaster CreateRasterHillShade(IRaster raster) { try { RasterSurfaceOpClass class2 = new RasterSurfaceOpClass(); IGeoDataset geoDataset = raster as IGeoDataset; double zFactor = Convert.ToDouble(textBoxX3.Text); if (zFactor <= 0) { MessageBox.Show("请指定大于0的正数!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(null); } object o = zFactor; double azimuth = slider2.Value; double altitude = slider1.Value; bool inModelShadows = false; if (cmbRenderType.SelectedIndex == 1) { inModelShadows = true; } IGeoDataset pGeoDataset = class2.HillShade(geoDataset, azimuth, altitude, inModelShadows, ref o); IRaster pRaster = (IRaster)pGeoDataset; ISaveAs2 pSaveAs = pRaster as ISaveAs2; IDataset pDataset = pSaveAs.SaveAs(m_ResultPath + ".tif", null, "TIFF"); System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset); MessageBox.Show("山体阴影计算完毕!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(pRaster); } catch (SystemException e) { MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } }
/// <summary> /// 计算碳密度 /// </summary> public Boolean Cal_carbonDensity() { string exp = coefficient + " * [Biomass]"; //栅格代数 IMapAlgebraOp mapAlgebraOp = null; IGeoDataset rasout = null; ISaveAs2 saveAs = null; try { //绑定符号 mapAlgebraOp = new RasterMapAlgebraOpClass(); mapAlgebraOp.BindRaster(rasterBiomass, "Biomass"); //执行 rasout = mapAlgebraOp.Execute(exp); //rasterDensity = (IRasterDataset)rasout; //删除原有输出文件 if (File.Exists(carbonDensity)) { File.Delete(carbonDensity); } //保存文件 saveAs = (ISaveAs2)rasout; //saveAs.SaveAs(outFile, workspace, "TIFF"); IDataset o = saveAs.SaveAs(carbonDensity, null, "TIFF"); if (o != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(o); } return(true); } catch (Exception ex) { XtraMessageBox.Show("计算碳密度失败!\r\n" + ex.Message); return(false); } finally { //释放 //rasterBiomass = null; if (rasterBiomass != null) { Marshal.ReleaseComObject(rasterBiomass); } if (saveAs != null) { Marshal.ReleaseComObject(saveAs); } if (rasout != null) { Marshal.ReleaseComObject(rasout); } if (mapAlgebraOp != null) { Marshal.ReleaseComObject(mapAlgebraOp); } } }
/// <summary> /// 保存栅格为输出文件 /// </summary> /// <param name="raster"></param> /// <param name="outFile"></param> /// <returns></returns> public static void SaveRasterByISaveAs(IRaster raster, string outFile) { //保存结果,要用ISaveAs来保存 ISaveAs2 saveAs = raster as ISaveAs2; if (saveAs != null) { saveAs.SaveAs(outFile, null, "IMAGINE Image"); } }
public IRaster CreateRasterAspect(IRaster raster) { try { RasterSurfaceOpClass class2 = new RasterSurfaceOpClass(); IGeoDataset geoDataset = raster as IGeoDataset; IGeoDataset pGeoDataset = class2.Aspect(geoDataset); IRaster pRaster = (IRaster)pGeoDataset; ISaveAs2 pSaveAs = pRaster as ISaveAs2; IDataset pDataset = pSaveAs.SaveAs(m_ResultPath + ".tif", null, "TIFF"); System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset); MessageBox.Show("坡向计算完毕!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return(pRaster); } catch (SystemException e) { MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } }
public bool SaveAs(bool bSetRepresentationType = false, rstRepresentationType representationType = rstRepresentationType.DT_ATHEMATIC, bool bUseMessagebox = true) { object editValue = this.m_checkedCmbBand.EditValue; bool result; if (editValue == null) { XtraMessageBox.Show("请设置输出波段!", "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); result = false; } else if (string.IsNullOrEmpty(this.m_sOutputPath)) { XtraMessageBox.Show("请选择文件输出路径!", "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); result = false; } else { FileInfo fileInfo = new FileInfo(this.m_sOutputPath); if (fileInfo.Exists) { if (XtraMessageBox.Show("此文件已存在,是否覆盖?", "提示信息", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Asterisk) != System.Windows.Forms.DialogResult.OK) { result = false; return(result); } fileInfo.Delete(); } IRaster raster = this.m_raster; string[] array = editValue.ToString().Split(new char[] { ',' }); if (array.Length != this.m_bandList.Count) { IRaster raster2 = ((this.m_raster as IRaster2).RasterDataset as IRasterDataset3).CreateRaster(); IRasterProps rasterProps = raster2 as IRasterProps; rasterProps.Width = (this.m_raster as IRasterProps).Width; rasterProps.Height = (this.m_raster as IRasterProps).Height; IRasterBandCollection rasterBandCollection = raster2 as IRasterBandCollection; IRasterBandCollection rasterBandCollection2 = (this.m_raster as IRaster2).RasterDataset as IRasterBandCollection; for (int i = 0; i < rasterBandCollection2.Count; i++) { IRasterBand rasterBand = rasterBandCollection2.Item(i); string[] array2 = array; for (int j = 0; j < array2.Length; j++) { string text = array2[j]; if (text.Trim() == rasterBand.Bandname) { rasterBandCollection.AppendBand(rasterBand); break; } } } raster = raster2; } this.SetResamplingMethod(raster, this.m_cmbResamplingType); this.SetPixelType(raster, this.m_cmbPixelType); if (bSetRepresentationType) { this.SetRepresentationType(raster, representationType); } frmWaitDialog frmWait = new frmWaitDialog("正在输出......", "提示信息"); IWorkspace workspace = null; string text2 = "输出成功!"; //Logger logger = new Logger(); try { frmWait.Owner = this.m_frm; frmWait.TopMost = false; string text3 = this.m_cmbOutputType.Text; ISaveAs2 saveAs = raster as ISaveAs2; if (!saveAs.CanSaveAs(text3)) { XtraMessageBox.Show("不支持指定像素类型或文件格式的输出!", "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); result = false; } else { IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(this.m_sOutputPath), 0); IDataset o = saveAs.SaveAs(Path.GetFileName(this.m_sOutputPath), workspace, text3); if (o != null) { Marshal.ReleaseComObject(o); } result = true; } } catch (Exception ex) { text2 = "输出失败!"; result = false; } finally { if (workspace != null) { Marshal.ReleaseComObject(workspace); } frmWait.Close(); if (bUseMessagebox) { XtraMessageBox.Show(text2, "提示信息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Asterisk); } } } return(result); }
/// <summary> /// Raster图层导入到数据库 /// </summary> /// <param name="dbWorkspace">数据库</param> /// <param name="strRasterFileDir">本地栅格图层路径</param> /// <param name="strRasterFileName">本地栅格图层名称</param> /// <param name="strOutName">数据库栅格图层名称</param> /// <returns></returns> public IRasterDataset RasterFileIntoGDB(IWorkspace dbWorkspace, string strRasterFileDir, string strRasterFileName, string strOutName) { IWorkspace pSdeWorkSpace = dbWorkspace; try { //判断是否有重名现象 IWorkspace2 pWS2 = pSdeWorkSpace as IWorkspace2; //如果名称已存在 if (pWS2.get_NameExists(esriDatasetType.esriDTRasterDataset, strOutName)) { DialogResult result; result = MessageBox.Show("栅格文件名 " + strOutName + " 在数据库中已存在!" + "\r是否覆盖?", "相同文件名", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); //覆盖原栅格要素 if (result == DialogResult.Yes) { IRasterWorkspaceEx pRWs = pSdeWorkSpace as IRasterWorkspaceEx; IDataset pDataset = pRWs.OpenRasterDataset(strOutName) as IDataset; pDataset.Delete(); pDataset = null; } else if (result == DialogResult.No) { //不覆盖,则退出for循环,忽略这个要素,转入下一个要素的导入 return(null); } } IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass(); IWorkspace pWs = pRasterWsFac.OpenFromFile(strRasterFileDir, 0); IRasterDataset pRasterDs = null; IRasterWorkspace pRasterWs; if (!(pWs is IRasterWorkspace)) { MessageBox.Show("错误信息:" + strRasterFileDir + "不是栅格工作空间。"); return(null); } pRasterWs = pWs as IRasterWorkspace; pRasterDs = pRasterWs.OpenRasterDataset(strRasterFileName); ISaveAs2 saveAs2 = (ISaveAs2)pRasterDs; IRasterStorageDef rasterStorageDef = new RasterStorageDefClass(); IRasterStorageDef2 rasterStorageDef2 = (IRasterStorageDef2)rasterStorageDef; rasterStorageDef2.CompressionType = esriRasterCompressionType.esriRasterCompressionJPEG2000; rasterStorageDef2.CompressionQuality = 50; rasterStorageDef2.Tiled = true; rasterStorageDef2.TileHeight = 128; rasterStorageDef2.TileWidth = 128; saveAs2.SaveAsRasterDataset(strOutName, pSdeWorkSpace, "JP2", rasterStorageDef2); return(pRasterDs); } catch (Exception ex) { MessageBox.Show("错误信息:" + ex.Message); return(null); } }
/// <summary> /// 计算生物量 /// </summary> public Boolean Cal_Biomass() { //获取公式中栅格符号 string[] ss = expression.Split(new char[2] { '[', ']' }); List <string> rasSymbols = new List <string>(); for (int i = 1; i < ss.Length; i = i + 2) { if (rasSymbols.Contains(ss[i]) == false) { rasSymbols.Add(ss[i]); } } //栅格代数 IMapAlgebraOp mapAlgebraOp = null; IRasterDataset rasterDataset = null; ISaveAs2 saveAs = null; try { //判断数量是否一致 if (rasSymbols.Count > index.Count) { XtraMessageBox.Show("运算表达式有错误!"); return(false); } //读取和绑定栅格 mapAlgebraOp = new RasterMapAlgebraOpClass(); foreach (string key in rasSymbols) { rasterDataset = RasterOP.OpenFileRasterDataset(index[key]); mapAlgebraOp.BindRaster((IGeoDataset)rasterDataset, key); } //执行 rasterBiomass = mapAlgebraOp.Execute(expression); //删除原有输出文件 if (File.Exists(Biomass)) { File.Delete(Biomass); } //保存文件 saveAs = (ISaveAs2)rasterBiomass; //saveAs.SaveAs(outFile, workspace, "TIFF"); IDataset o = saveAs.SaveAs(Biomass, null, "TIFF"); if (o != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(o); } return(true); } catch (Exception ex) { XtraMessageBox.Show("计算森林生物量失败!\r\n" + ex.Message); return(false); } finally { //释放 if (rasterDataset != null) { Marshal.ReleaseComObject(rasterDataset); } //if (saveAs != null) // Marshal.ReleaseComObject(saveAs); if (mapAlgebraOp != null) { Marshal.ReleaseComObject(mapAlgebraOp); } } }
//采用另一种方法实现互换XY,不会改变影像的分辨率 public bool NorthEastToEastNorth(IRasterLayer pRasterLayer, string szFilename)//坐标系x,y变换 { if (pRasterLayer == null || szFilename == null) { return(false); } try { ITransformationOp dstTrans = new RasterTransformationOpClass(); IRasterAnalysisEnvironment pDstAnalysisEnvironment = dstTrans as IRasterAnalysisEnvironment; if (pDstAnalysisEnvironment == null) { return(false); } //设置分辨率 IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; IRasterProps pProps = pRaster2 as IRasterProps; double dbCellSizeX = pProps.MeanCellSize().X; double dbCellSizeY = pProps.MeanCellSize().Y; double dbCellSizeMean = (dbCellSizeX + dbCellSizeY) / 2; //pDstAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSizeMean); //定义原始数据集和目标数据集 IGeoDataset pSrcGeoDataset = pRasterLayer.Raster as IGeoDataset; IGeoDataset pDstGeoDataset = null; IGeoDataset pTmpGeoDataset = null; //顺时针旋转90度 IPoint pt = new PointClass(); pt.X = 0; pt.Y = 0; pTmpGeoDataset = dstTrans.Rotate(pSrcGeoDataset, esriGeoAnalysisResampleEnum.esriGeoAnalysisResampleCubic, 90, pt); //pDstGeoDataset = pTmpGeoDataset; //水平旋转 pSrcGeoDataset = dstTrans.Flip(pTmpGeoDataset); //由于翻转是以图像中心为界,所以要加上偏移量 IEnvelope pExtent = pSrcGeoDataset.Extent; double dbCenterY = (pExtent.UpperLeft.Y + pExtent.LowerRight.Y) / 2; double dbDeltaX = 0; double dbDeltaY = -dbCenterY * 2; //pDstGeoDataset = dstTrans.Flip(pTmpGeoDataset); pDstGeoDataset = dstTrans.Shift(pSrcGeoDataset, dbDeltaX, dbDeltaY, null); if (pDstGeoDataset == null) { return(false); } IRasterLayer pLayer = new RasterLayerClass(); pLayer.CreateFromDataset(pDstGeoDataset as IRasterDataset); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace inmemWor = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szFilename), 0); ISaveAs2 sa = pDstGeoDataset as ISaveAs2; //IRaster2 pR2 = ((IRasterDataset3)pDstGeoDataset).CreateDefaultRaster() as IRaster2; IRaster2 pR2 = pLayer.Raster as IRaster2; IRasterEdit pRe = pR2 as IRasterEdit; //pRe.Refresh(); // sa = ((IRasterDataset3)pDstGeoDataset).CreateDefaultRaster() as ISaveAs2; sa = pRe as ISaveAs2; if (sa != null) { sa.SaveAs(System.IO.Path.GetFileName(szFilename), inmemWor, "TIFF"); //sa.SaveAsRasterDataset() pRe.Refresh(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pRe); (pDstGeoDataset as IRasterDataset3).Refresh(); } IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); return(true); } catch (System.Exception ex) { MessageBox.Show(ex.Message); return(false); } }
protected override void OnClick() { try { ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager; if (VariableMaintainer.CurrentModel == EnumCurrentModel.Null) { MessageBox.Show(resourceManager.GetString("String168"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } Thread thread = VariableMaintainer.SimulationThread; if (thread != null) { if (thread.ThreadState != ThreadState.Stopped) { MessageBox.Show(resourceManager.GetString("String39"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } StructRasterMetaData structRasterMetaData = new StructRasterMetaData(); string model = ""; if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression) { model = resourceManager.GetString("String104"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN) { model = resourceManager.GetString("String102"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT) { model = resourceManager.GetString("String103"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Optimization_Area) { model = resourceManager.GetString("String167"); } VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String82") + model + resourceManager.GetString("String101") + DateTime.Now.ToShortTimeString()); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String58")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String58")); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression) { //ArcGIS操作在另一线程中执行效率降低很多,因此把数据读取及刷新操作在线程外执行 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName), out structRasterMetaData); if (VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName), -9999f); } //然后读取各变量影像 if (VariableMaintainer.CurrentFormLogisticCAWizard.IsUsingDefault) { foreach (string layerName in VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName) { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String14") + layerName + "....."); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String14") + layerName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.VaribaleImages.Add( ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName(layerName), -9999f)); } //获取最小空间范围 IRasterLayer rasterLayerStartImage = ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName); IRasterLayer rasterLayerEndImage = ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName); List <IRasterLayer> listVariablesLayers = new List <IRasterLayer>(); for (int i = 0; i < VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName.Count; i++) { listVariablesLayers.Add(ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName[i])); } ArcGISOperator.GetSmallestBound(rasterLayerStartImage, rasterLayerEndImage, listVariablesLayers, ref structRasterMetaData); VariableMaintainer.CurrentFormLogisticCAWizard.CurrentStructRasterMetaData = structRasterMetaData; } //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationLayerName = rasterName; LogisticRegreesionCA lrCA = new LogisticRegreesionCA(); lrCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; lrCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(lrCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN) { //今后应使用父类和接口进行重构 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName), out structRasterMetaData); //VariableMaintainer.CurrentANNCAWizard.CurrentStructRasterMetaData = structRasterMetaData; if (VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImageName), -9999f); } //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormANNCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormANNCAWizard.SimulationLayerName = rasterName; ANNCA annCA = new ANNCA(); annCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; annCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(annCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT) { //今后应使用父类和接口进行重构 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName), out structRasterMetaData); //VariableMaintainer.CurrentDTCAWizard.CurrentStructRasterMetaData = structRasterMetaData; if (VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImageName), -9999f); } //20170619添加限制层数据 //VariableMaintainer.CurrentDockableWindowOutput.AppendText("Add Restriction Layer " + // "ACOres" + ".....\n"); //VariableMaintainer.RestrictImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( // "ACOres"), -9999f); //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormDTCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormDTCAWizard.SimulationLayerName = rasterName; DecisionTreeCA dtCA = new DecisionTreeCA(); dtCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; dtCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(dtCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Optimization_Area) { if (!VariableMaintainer.IsACOUtilitySet || !VariableMaintainer.IsACOParametersSet) { MessageBox.Show(resourceManager.GetString("String166"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } AreaOptimizationACO areaOptimizationACO = new AreaOptimizationACO(); areaOptimizationACO.Initialize(VariableMaintainer.CurrentStructACOParameters, 1, false, VariableMaintainer.CurrentDockableWindowOutput, VariableMaintainer.CurrentDockableWindowGraphy, true); thread = new Thread(new ThreadStart(areaOptimizationACO.Run)); } else { MessageBox.Show(resourceManager.GetString("String168"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } VariableMaintainer.SimulationThread = thread; thread.SetApartmentState(ApartmentState.STA); thread.Start(); VariableMaintainer.CurrentTimer.Interval = 500; VariableMaintainer.CurrentTimer.Tick += new EventHandler(t_Tick); VariableMaintainer.CurrentTimer.Enabled = true; VariableMaintainer.CurrentTimer.Start(); ArcMap.Application.CurrentTool = null; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public float[,] GetSuitabilityData(string expression) { string[] splitedExpressionArray; bool isSplited = SplitExpression(expression, out splitedExpressionArray); if (isSplited == false) { MessageBox.Show("Suitibility Function Express Error", VariableMaintainer.CurrentResourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } //根据获取的文件名字符串去读取相应的栅格文件 List <float[, ]> listLayers = new List <float[, ]>(); structRasterMetaData = new StructRasterMetaData(); for (int i = 0; i < splitedExpressionArray.Length; i++) { if (i > 0 && i % 2 > 0) { string layerName = splitedExpressionArray[i]; if (i == 1) { listLayers.Add(ArcGISOperator.ReadRasterAndGetMetaData( ArcGISOperator.GetRasterLayerByName(layerName), out structRasterMetaData)); } else { listLayers.Add(ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName(layerName), structRasterMetaData.NoDataValue)); } } } if (listLayers.Count == 0) { MessageBox.Show("Please select layers for calculation!", VariableMaintainer.CurrentResourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } //读取全部文件后进行计算,生成适宜性图层数据,并进行归一化 float[,] suitabilityData = new float[structRasterMetaData.RowCount, structRasterMetaData.ColumnCount]; float min = 1, max = 0; Expression ex = new Expression("1+1"); //MathParser mathParser = new MathParser(); for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { bool isNullData = false; for (int k = 0; k < listLayers.Count; k++) { if (listLayers[k][i, j] == structRasterMetaData.NoDataValue) { isNullData = true; break; } } if (isNullData) { suitabilityData[i, j] = structRasterMetaData.NoDataValue; } else { string calculateExpression = ""; for (int w = 0; w < splitedExpressionArray.Length; w++) { if (w > 0 && w % 2 == 1) { calculateExpression += listLayers[w / 2][i, j]; } else { calculateExpression += splitedExpressionArray[w]; } } ex = new Expression(calculateExpression); suitabilityData[i, j] = Convert.ToSingle(ex.Evaluate()); //suitabilityData[i, j] = Convert.ToSingle(mathParser.Parse(calculateExpression, false)); if (suitabilityData[i, j] < min) { min = suitabilityData[i, j]; } if (suitabilityData[i, j] > max) { max = suitabilityData[i, j]; } } } } float[,] suitabilityData2 = new float[structRasterMetaData.RowCount, structRasterMetaData.ColumnCount]; for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { if (suitabilityData[i, j] == structRasterMetaData.NoDataValue) { suitabilityData2[i, j] = structRasterMetaData.NoDataValue; } else { suitabilityData2[i, j] = (suitabilityData[i, j] - min) / (max - min); } } } //将其他图层关闭,以免影响蚁群优化的刷新效果 for (int i = 0; i < VariableMaintainer.CurrentFoucsMap.LayerCount; i++) { if (VariableMaintainer.CurrentFoucsMap.get_Layer(i).Visible) { VariableMaintainer.CurrentFoucsMap.get_Layer(i).Visible = false; } } //显示适宜性图层 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "suitability" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, VariableMaintainer.CurrentResourceManager.GetString("String169")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(VariableMaintainer.CurrentResourceManager.GetString("String169") + rasterName + ".....\n"); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); IRasterLayer templateImageLayer = ArcGISOperator.GetRasterLayerByName( splitedExpressionArray[1].ToString()); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.DefaultOutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)templateImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer sutiabilityImageLayer = new RasterLayerClass(); sutiabilityImageLayer.CreateFromFilePath(VariableMaintainer.DefaultOutputFolder + @"\" + rasterName); //sutiabilityImageLayer.Renderer = templateImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)sutiabilityImageLayer); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.DefaultOutputFolder + @"\" + rasterName); ArcGISOperator.WriteRaster(simulationImageLayer, suitabilityData2); IRasterLayer l = ArcGISOperator.GetRasterLayerByName(rasterName); IRaster2 raster = simulationImageLayer.Raster as IRaster2; IPnt fromPnt = new PntClass(); fromPnt.SetCoords(0, 0); IPnt blockSize = new PntClass(); blockSize.SetCoords(simulationImageLayer.ColumnCount, simulationImageLayer.RowCount); IPixelBlock pixelBlock = ((IRaster)raster).CreatePixelBlock(blockSize); l.Raster.Read(fromPnt, pixelBlock); ((IRasterEdit)l.Raster).Refresh(); IActiveView activeView = VariableMaintainer.CurrentFoucsMap as IActiveView; activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); return(suitabilityData2); }
/// <summary> /// 求和. /// </summary> /// <returns>Boolean.</returns> public Boolean Sum() { //栅格代数 string exp = string.Empty; IMapAlgebraOp mapAlgebraOp = null; IRasterDataset rasterDataset = null; IGeoDataset rasout = null; ISaveAs2 saveAs = null; try { //读取和绑定栅格 mapAlgebraOp = new RasterMapAlgebraOpClass(); //根据文件列表生成计算公式和绑定栅格 for (int i = 0; i < fileList.Count; i++) { string symbol = "[ras" + i + "]"; rasterDataset = RasterOP.OpenFileRasterDataset(fileList[i]); mapAlgebraOp.BindRaster((IGeoDataset)rasterDataset, symbol.Substring(1, symbol.Length - 2)); exp = exp + symbol + " + "; } exp = exp.Substring(0, exp.Length - 3); //执行 rasout = mapAlgebraOp.Execute(exp); //删除原有输出文件 if (File.Exists(outFile)) { File.Delete(outFile); } //保存文件 saveAs = (ISaveAs2)rasout; //saveAs.SaveAs(outFile, workspace, "TIFF"); IDataset o = saveAs.SaveAs(outFile, null, "TIFF"); if (o != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(o); } return(true); } catch (Exception ex) { MessageBox.Show("计算生物量失败!/n" + ex.Message); return(false); } finally { //释放 if (saveAs != null) { Marshal.ReleaseComObject(saveAs); } if (rasout != null) { Marshal.ReleaseComObject(rasout); } if (rasterDataset != null) { Marshal.ReleaseComObject(rasterDataset); } if (mapAlgebraOp != null) { Marshal.ReleaseComObject(mapAlgebraOp); } } }
//private rstPixelType GetRasterPixelType(string strType) //{ // if (strType == rstPixelType.PT_CHAR.ToString()) // { // return rstPixelType.PT_CHAR; // } // else if (strType == rstPixelType.PT_UCHAR.ToString()) // { // return rstPixelType.PT_UCHAR; // } // else if (strType == rstPixelType.PT_SHORT.ToString()) // { // return rstPixelType.PT_SHORT; // } // else if (strType == rstPixelType.PT_USHORT.ToString()) // { // return rstPixelType.PT_USHORT; // } // else if (strType == rstPixelType.PT_LONG.ToString()) // { // return rstPixelType.PT_LONG; // } // else if (strType == rstPixelType.PT_ULONG.ToString()) // { // return rstPixelType.PT_ULONG; // } // else if (strType == rstPixelType.PT_CSHORT.ToString()) // { // return rstPixelType.PT_CSHORT; // } // else if (strType == rstPixelType.PT_CLONG.ToString()) // { // return rstPixelType.PT_CLONG; // } // else if (strType == rstPixelType.PT_FLOAT.ToString()) // { // return rstPixelType.PT_FLOAT; // } // else if (strType == rstPixelType.PT_DOUBLE.ToString()) // { // return rstPixelType.PT_DOUBLE; // } // return rstPixelType.PT_CHAR; //} //private rstResamplingTypes GetRasterResample(string strType) //{ // if (strType == "NearestNeighbor") // { // return rstResamplingTypes.RSP_NearestNeighbor; // } // else if (strType == "BilinearInterpolation") // { // return rstResamplingTypes.RSP_BilinearInterpolation; // } // else if (strType == "CubicConvolution") // { // return rstResamplingTypes.RSP_CubicConvolution; // } // else if (strType == "Majority") // { // return rstResamplingTypes.RSP_Majority; // } // return rstResamplingTypes.RSP_NearestNeighbor; //} #endregion private bool ExportToTif() { if (!txtOutData.Text.EndsWith("tif")) { MessageBox.Show("输出文件名不是tif文件!"); return(false); } String strFullName = txtOutData.Text; string strPath = System.IO.Path.GetDirectoryName(strFullName); //导出文件路径 string strName = System.IO.Path.GetFileName(strFullName); //导出文件名 try { IRasterBandCollection bandsOut = m_pRaster as IRasterBandCollection; IRasterBandCollection rasterBands = m_pRaster.RasterDataset as IRasterBandCollection; double[] dNodata; int nBandOut = 1; //IRaster pRasterOut = null; IRasterBand pBand = null; if (comboBoxExBands.SelectedIndex == 0)//所有波段 { //添加其他波段 for (int i = 3; i < rasterBands.Count; i++) { pBand = rasterBands.Item(i); bandsOut.AppendBand(pBand); } nBandOut = rasterBands.Count; } else { #region 原代码 //pRasterOut = new RasterClass(); //IRasterBandCollection pRB2 = pRasterOut as IRasterBandCollection; //pRB2.AppendBand(rasterBands.Item(comboBoxExBands.SelectedIndex - 1)); //m_pRasterProps = pRasterOut as IRasterProps; #endregion //导出单波段时,不能用Clear(),会清除图层的几何校正属性 int nOut = bandsOut.Count; for (int i = 0; i < nOut; i++) { bandsOut.Remove(i); } pBand = rasterBands.Item(comboBoxExBands.SelectedIndex - 1); bandsOut.AppendBand(pBand); } //重新设置NoData dNodata = new double[nBandOut]; if (!string.IsNullOrEmpty(textNoData.Text)) { for (int i = 0; i < nBandOut; i++) { dNodata[i] = Convert.ToDouble(textNoData.Text); } m_pRasterProps.NoDataValue = dNodata; } //else //{ // for (int i = 0; i < nBandOut; i++) // { // dNodata[i] = ClsGDBDataCommon.getNoDataValue((rasterBands.Item(i) as IRasterProps).NoDataValue);// Convert.ToDouble((rasterBands.Item(i) as IRasterProps).NoDataValue); // } // m_pRasterProps.NoDataValue = dNodata; //} IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass(); IWorkspace pWS = pWSF.OpenFromFile(System.IO.Path.GetDirectoryName(txtOutData.Text), 0); //导出时要保持分辨率和行列数 m_pRasterProps.Width = Convert.ToInt32(txtOutColumns.Text); m_pRasterProps.Height = Convert.ToInt32(txtOutRows.Text); double dcellSizeX = double.Parse(txtCellSizeX.Text); double dcellSizeY = double.Parse(txtCellSizeY.Text); IEnvelope pEnvelope = new EnvelopeClass(); pEnvelope.XMin = m_pRasterProps.Extent.UpperLeft.X; pEnvelope.YMax = m_pRasterProps.Extent.UpperLeft.Y; pEnvelope.XMax = m_pRasterProps.Extent.UpperLeft.X + m_pRasterProps.Width * dcellSizeX; pEnvelope.YMin = m_pRasterProps.Extent.UpperLeft.Y - m_pRasterProps.Height * dcellSizeY; m_pRasterProps.Extent = pEnvelope; //设置存储位数 m_pRasterProps.PixelType = (rstPixelType)cmbPixelType.SelectedIndex; ISaveAs2 pSaveAs = m_pRasterProps as ISaveAs2; IRasterStorageDef pRSDef = new RasterStorageDefClass(); IRasterStorageDef2 pRsDef2 = pRSDef as IRasterStorageDef2; //将存储栅格的分辨率设置为与原始图像相同,其实经过上面行列计算之后已经是相同的 IPnt pPntdec = new PntClass(); pPntdec.X = dcellSizeX; pPntdec.Y = dcellSizeY; pRsDef2.CellSize = pPntdec; pRsDef2.PyramidResampleType = (rstResamplingTypes)cmbResample.SelectedIndex; IRasterDataset pDataset = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(txtOutData.Text), pWS, "TIFF", pRSDef); IRasterDatasetEdit3 rasterEdit3 = pDataset as IRasterDatasetEdit3; //rasterEdit3.DeleteStats();//This method is avaliable only on raster datasets in File and ArcSDE geodatabases. rasterEdit3.ComputeStatisticsHistogram(1, 1, null, true); //导出数据之后要恢复图像的原始属性 m_pRasterProps.SpatialReference = m_pSpatialRef; m_pRasterProps.Extent = m_Envelope; m_pRasterProps.Width = m_nCols; m_pRasterProps.Height = m_nRows; //加到当前地图中 IRasterLayer layerNew = new RasterLayerClass(); layerNew.CreateFromDataset(pDataset); m_pMap.AddLayer(layerNew); IActiveView activeView = m_pMap as IActiveView; activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); return(true); } catch (Exception exc) { MessageBox.Show(exc.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } }
//拉伸到灰度图像 private bool stretchToGrayImage(IRaster pSrcRaster, string szOutputFilename, double dbMinThreshold = 0.02, double dbMaxThreshold = 0.98) { try { if (pSrcRaster == null || szOutputFilename == null) { return(false); } //深拷贝 IClone pSrcClone = pSrcRaster as IClone; IClone pDstClone = pSrcClone.Clone(); IRaster pDstRaster = pDstClone as IRaster; IRaster2 pDstRaster2 = pDstRaster as IRaster2; IRasterProps pRasterProps = pDstRaster as IRasterProps; //原始统计信息 bool bFlag = false; IRasterBand pRasterBand = (pDstRaster as IRasterBandCollection).Item(0); pRasterBand.HasStatistics(out bFlag); if (!bFlag) { pRasterBand.ComputeStatsAndHist(); } //得到原始栅格影像的最大最小值和步长 double dbSrcMaxValue = pRasterBand.Statistics.Maximum; double dbSrcMinValue = pRasterBand.Statistics.Minimum; double dbSrcStep = (dbSrcMaxValue - dbSrcMinValue) / 256; double dbStretchMaxValue = pRasterBand.Statistics.Maximum; double dbStretchMinValue = pRasterBand.Statistics.Minimum; #region 灰度映射,利用重分类来做 //第一次重分类 IReclassOp reclassOp = new RasterReclassOpClass(); INumberRemap numberRemap = new NumberRemapClass(); for (int i = 0; i < 256; i++) { numberRemap.MapRange(dbSrcMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i); } IRaster pRasterTemp = reclassOp.ReclassByRemap((IGeoDataset)(pDstRaster2.RasterDataset), (IRemap)numberRemap, true) as IRaster; IRaster2 pRasterTemp2 = pRasterTemp as IRaster2; IRasterProps pRasterTempProps = pRasterTemp as IRasterProps; //得到属性表 IRasterDatasetEdit3 pRasterDatasetEdit3 = pRasterTemp2.RasterDataset as IRasterDatasetEdit3; pRasterDatasetEdit3.ComputeStatisticsHistogram(1, 1, null, true); IRasterBand rasterBand = (pRasterTempProps as IRasterBandCollection).Item(0); IRasterHistogram rasterHistogram = rasterBand.Histogram; IRasterStatistics rasterStatistics = rasterBand.Statistics; double[] pHistogramCount = (double[])rasterHistogram.Counts; int nCurrentCount = 0; int nIndex = 0; int nPixelCount = 0;//pRasterProps.Width * pRasterProps.Height; //double dSum = 0.0; for (int i = 0; i < 256; i++) { nPixelCount += (int)pHistogramCount[i]; } //得到拉伸的最大最小值 while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMinThreshold) { nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]); } dbStretchMinValue = nIndex * dbSrcStep + dbSrcMinValue; while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMaxThreshold) { nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]); } dbStretchMaxValue = nIndex * dbSrcStep + dbSrcMinValue; dbSrcStep = (dbStretchMaxValue - dbStretchMinValue) / 256; #endregion #region 拉伸 INumberRemap numberRemapForStretch = new NumberRemapClass(); numberRemapForStretch.MapRange(dbSrcMinValue, dbStretchMinValue + dbSrcStep, 0); for (int i = 1; i < 255; i++) { numberRemapForStretch.MapRange(dbStretchMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i); } numberRemapForStretch.MapRange(dbStretchMinValue + 255 * dbSrcStep, dbSrcMaxValue, 255); IRaster pRasterStretch = reclassOp.ReclassByRemap((IGeoDataset)((pDstRaster as IRaster2).RasterDataset), (IRemap)numberRemapForStretch, true) as IRaster; IRasterProps pRasterStretchProps = pRasterStretch as IRasterProps; #region 注释代码 ////拉伸 //IPixelBlock3 pixelBlock3 = null; //IRasterCursor rasterCursor = (pDstRaster as IRaster2).CreateCursorEx(null);//null时为128*128 //do //{ // pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; // int nWidth = pixelBlock3.Width; // int nHeight = pixelBlock3.Height; // System.Array pixels = (System.Array)pixelBlock3.get_PixelData(0); // for (int m = 0; m < nWidth; m++) // { // for (int n = 0; n < nHeight; n++) // { // double dbSrcValue = Convert.ToDouble(pixels.GetValue(m, n)); // if (double.IsNaN(dbSrcValue) || dbSrcValue == dbNoDataValue) // continue; // if (dbSrcValue >= dbStretchMaxValue) // pixels.SetValue(255, m, n); // else if (dbSrcValue <= dbStretchMinValue) // pixels.SetValue(0, m, n); // else // { // byte dbDstValue = Convert.ToByte((dbSrcValue - dbStretchMinValue) / (dbStretchMaxValue - dbStretchMinValue) * 255); // pixels.SetValue(dbDstValue, m, n); // } // } // } // pixelBlock3.set_PixelData(0, (System.Array)pixels); // //修改数据 // pRasterEdit.Write(rasterCursor.TopLeft, pixelBlock3 as IPixelBlock); // pRasterEdit.Refresh(); //} while (rasterCursor.Next() == true); #endregion #endregion #region 存储数据 IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace inmemWor = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szOutputFilename), 0); pRasterStretchProps.PixelType = rstPixelType.PT_UCHAR; ISaveAs2 pSaveAs = pRasterStretchProps as ISaveAs2; if (pSaveAs == null) { return(false); } IRasterStorageDef pRSDef = new RasterStorageDefClass(); IRasterDataset pDataset = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(szOutputFilename), inmemWor, "TIFF", pRSDef); (pDataset as IRasterDataset3).Refresh(); //IRasterEdit pRasterEdit = pDstRaster as IRasterEdit; IRasterEdit pRasterTempEdit = pRasterTemp as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterTempEdit); IRasterEdit pRasterStretchEdit = pRasterStretch as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterStretchEdit); #endregion return(true); } catch (System.Exception ex) { MessageBox.Show(ex.Message); return(false); } }
private void ExportToTif() { string strFloder = txtOutData.Text; for (int i = 0; i < m_pMapControl.Map.LayerCount; i++) { if (m_pMapControl.Map.get_Layer(i) is IRasterLayer) { //导入数据 IRasterLayer pRLayer = m_pMapControl.Map.get_Layer(i) as IRasterLayer; IRaster2 pRaster = pRLayer.Raster as IRaster2; IRawBlocks pRawBlocks = pRaster as IRawBlocks; IRasterInfo pRInfo = pRawBlocks.RasterInfo; IPnt pPnt = pRInfo.CellSize; double dcellSize = pPnt.X; double dcellsizeY = pPnt.Y; string sCellSize = Convert.ToInt32(dcellSize * 10).ToString(); string strFileName = "R" + sCellSize + "_" + pRLayer.Name; string strFullName = txtOutData.Text + "\\" + strFileName; //设置空间参考 ISpatialReference pSpatialRef; if (rdoLayer.Checked)//与原图相同 { IGeoDataset pGeo = (IGeoDataset)pRLayer; pSpatialRef = pGeo.SpatialReference; } else//与工作空间相同 { pSpatialRef = m_pMapControl.Map.SpatialReference; } try { //IRasterLayerExport pRLayerExport = new RasterLayerExportClass(); //pRLayerExport.RasterLayer = pRLayer; //pRLayerExport.SpatialReference = pSpatialRef; //pRLayerExport.SetSize(pRLayer.ColumnCount, pRLayer.RowCount); IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass(); IWorkspace pWS = pWSF.OpenFromFile(txtOutData.Text, 0); //IRasterDataset pRDset = pRLayerExport.Export(pWS, strFileName, "TIFF"); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pRDset); IRasterProps pRasterProps = pRaster as IRasterProps; //pRasterProps.PixelType = pRInfo.PixelType; //投影发生变化,栅格的分辨率会发生变化 pRasterProps.SpatialReference = pSpatialRef; IRawBlocks pRBlocks = pRasterProps as IRawBlocks; IRasterInfo pRaInfo = pRBlocks.RasterInfo; //计算出重投影之后对应的栅格的行数和列数,行列数改变之后,它对应的栅格的分辨率也会变化为原始栅格的分辨率 //如果没有下面的计算行列的步骤,重投影之后的分辨率和原始影响的分辨率不同,行列数相同 pRasterProps.Width = Convert.ToInt32(pRasterProps.MeanCellSize().X *pRLayer.ColumnCount / dcellSize); pRasterProps.Height = Convert.ToInt32(pRasterProps.MeanCellSize().Y *pRLayer.RowCount / dcellsizeY); IEnvelope pEnvelope = new EnvelopeClass(); pEnvelope.XMin = pRasterProps.Extent.UpperLeft.X; pEnvelope.YMax = pRasterProps.Extent.UpperLeft.Y; pEnvelope.XMax = pRasterProps.Extent.UpperLeft.X + pRasterProps.Width * dcellSize; pEnvelope.YMin = pRasterProps.Extent.UpperLeft.Y - pRasterProps.Height * dcellsizeY; pRasterProps.Extent = pEnvelope; ISaveAs2 pSaveAs = pRasterProps as ISaveAs2; IRasterStorageDef pRSDef = new RasterStorageDefClass(); //将存储栅格的分辨率设置为与原始图像相同,其实经过上面行列计算之后已经是相同的 IPnt pPntdec = new PntClass(); pPntdec.X = dcellSize; pPntdec.Y = dcellsizeY; pRSDef.CellSize = pPntdec; IRasterDataset pDataset = pSaveAs.SaveAsRasterDataset(strFileName, pWS, "TIFF", pRSDef); pDataset.PrecalculateStats(0); System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset); } catch (Exception exc) { //MessageBox.Show(exc.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } this.Close(); }