private void btnOpenRaster_Click(object sender, EventArgs e) { using (var dialog = new OpenFileDialog()) { dialog.Filter = "*.*|*.*"; dialog.CheckFileExists = true; if (dialog.ShowDialog() == DialogResult.OK) { var layer = new RasterLayer() { Alias = dialog.FileName, Visible = true }; layer.DataSourceNeeded += new EventHandler<RasterDataSourceEventArgs>(layer_DataSourceNeeded); layer.DataProviderParameters.Add("file_name", dialog.FileName); layer.DataSourceReadyToRelease += new EventHandler<RasterDataSourceEventArgs>(layer_DataSourceReadyToRelease); var width = 0; var height = 0; using (GDALRasterProvider gdal = new GDALRasterProvider(dialog.FileName)) { width = gdal.Width; height = gdal.Height; } layer.Binding = new RasterLayer.RasterBinding(0, 0, new Coordinate() { X = 0, Y = height }, 1, 1); layer.LoadRasterPreview(new BoundingRectangle(0, 0, width, height), width/mapControl.ClientSize.Width); _map.AddLayer(layer); SetViewBox(); } } }
public void BitmapGetter_DisposeOnChange() { var raster = Raster.Create(FileTools.GetTempFileName(".bgd"), String.Empty, 1, 1, 1, typeof(byte), new[] { String.Empty }); try { var target = new RasterLayer(raster) { BitmapGetter = new ImageData() }; var bitmapGetter = (DisposeBase)target.BitmapGetter; target.BitmapGetter = null; Assert.IsTrue(bitmapGetter.IsDisposed); } finally { File.Delete(raster.Filename); } }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. //Get a path to the raster workspace and create a RasterWorkspace object Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IRasterWorkspace2 rasterWorkspace = (IRasterWorkspace2) workspaceFactory.OpenFromFile("\\\\Filepath\\ToRaster\\Folder", 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset("DEM_Resample.tif"); //Create a raster layer to get the raster object from it IRasterLayer rasterLayer = new RasterLayer(); rasterLayer.CreateFromDataset(rasterDataset); IRaster raster = rasterLayer.Raster; //Get the raster properties so we can modify them later and get details about them if we so choose. IRasterProps rasterProps = raster as IRasterProps; double cellSize = 60; //Declate a new spatial reference if you want to change the spatial reference used. ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); ISpatialReference2 srReference = srFactory.CreateProjectedCoordinateSystem(26917) as ISpatialReference2; //Create an IRasterGeometryProc object as this has the projectFast method we are looking for. IRasterGeometryProc rasterGeometryProc = new RasterGeometryProc(); rasterGeometryProc.ProjectFast(rasterProps.SpatialReference, rstResamplingTypes.RSP_NearestNeighbor, ((object)cellSize), raster); //Create a new rasterBandCollection to store the raster in and save it there. IRasterBandCollection rasterBandCollection = raster as IRasterBandCollection; String outName = "NewImage.tif"; String outType = "TIFF"; rasterBandCollection.SaveAs(outName, ((IWorkspace)rasterWorkspace), outType); Console.WriteLine("DONE"); Console.ReadLine(); //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); }
private async void Initialize() { // Create a new map MyMapView.Map = new Map(Basemap.CreateLightGrayCanvas()); // Get the full path string geoPackagePath = GetGeoPackagePath(); try { // Open the GeoPackage GeoPackage myGeoPackage = await GeoPackage.OpenAsync(geoPackagePath); // Read the raster images and get the first one Raster gpkgRaster = myGeoPackage.GeoPackageRasters.FirstOrDefault(); // Make sure an image was found in the package if (gpkgRaster == null) { return; } // Create a layer to show the raster RasterLayer newLayer = new RasterLayer(gpkgRaster); await newLayer.LoadAsync(); // Set the viewpoint await MyMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent)); // Add the image as a raster layer to the map (with default symbology) MyMapView.Map.OperationalLayers.Add(newLayer); } catch (Exception e) { MessageBox.Show(e.ToString(), "Error"); } }
public IRasterLayer AddRasterFile(string filename, IPolygon polygon) { try { FileInfo fi = new FileInfo(filename); if (_directory == "") { _directory = fi.Directory.FullName; } else if (_directory.ToLower() != fi.Directory.FullName.ToLower()) { return(null); } if (fi.Extension.ToLower() == ".sid" || fi.Extension.ToLower() == ".jp2") { MrSidFileClass rasterClass = (polygon == null) ? new MrSidFileClass(this, filename) : new MrSidFileClass(this, filename, polygon); RasterLayer layer = new RasterLayer(rasterClass); if (rasterClass.isValid) { _layers.Add(layer); } return(layer); } else { RasterFileClass rasterClass = (polygon == null) ? new RasterFileClass(this, filename) : new RasterFileClass(this, filename, polygon); RasterLayer layer = new RasterLayer(rasterClass); if (rasterClass.isValid) { _layers.Add(layer); } return(layer); } } catch { } return(null); }
private async void Initialize() { // Create a map with a streets basemap. Map myMap = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); try { // Create and load a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Once the layer is loaded, enable the button to apply a new renderer. _applyRendererButton.Enabled = true; // Create a viewpoint with the raster's full extent. Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent); // Set the initial viewpoint for the map. myMap.InitialViewpoint = fullRasterExtent; // Add the layer to the map. myMap.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = myMap; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
public static Proj4ProjectionInfo GetProj4ProjectionInfo(this Layer layer) { Proj4ProjectionInfo proj4ProjectionInfo = null; FeatureLayer featureLayer = layer as FeatureLayer; RasterLayer rasterLayer = layer as RasterLayer; if (featureLayer != null) { Proj4Projection proj4Projection = featureLayer.FeatureSource.Projection as Proj4Projection; Proj4Projection managedProj4Projection = featureLayer.FeatureSource.Projection as Proj4Projection; if (proj4Projection != null) { proj4ProjectionInfo = new UnManagedProj4ProjectionInfo(proj4Projection); } else if (managedProj4Projection != null) { proj4ProjectionInfo = new ManagedProj4ProjectionInfo(managedProj4Projection); } } else if (rasterLayer != null) { Proj4Projection proj4Projection = rasterLayer.ImageSource.Projection as Proj4Projection; Proj4Projection managedProj4Projection = rasterLayer.ImageSource.Projection as Proj4Projection; if (proj4Projection != null) { proj4ProjectionInfo = new UnManagedProj4ProjectionInfo(proj4Projection); } else if (managedProj4Projection != null) { proj4ProjectionInfo = new ManagedProj4ProjectionInfo(managedProj4Projection); } } return(proj4ProjectionInfo); }
protected override void OnMouseUp(MouseEventArgs arg) { try { IPoint pPoint; //Point object for clicked location pPoint = m_pMxDoc.CurrentLocation; //Create string variable to hold the field name in the ortho index string orthoField = "ORTHOID"; //Call method to get value of clicked index string strFieldValue; strFieldValue = getFeatureVal.featureUtility(pPoint, m_pOrthoIndexLayer, orthoField); //Create a Raster Layer object IRasterLayer pRLayer; pRLayer = new RasterLayer(); //Set the path to the selected image pRLayer.CreateFromFilePath("C:/Users/micha/Documents/GEOG 489/Lesson_3/Data/orthos/" + strFieldValue + ".tif"); pRLayer.Name = "Tile " + strFieldValue; //Update layer name //Add the ortho image to the map m_pMap.AddLayer(pRLayer); //Move the image to the bottom in the TOC m_pMap.MoveLayer(pRLayer, m_pMap.LayerCount - 1); //Update the map contents m_pMxDoc.UpdateContents(); } catch (System.Exception ex) { MessageBox.Show("Error: This index does not have an orthophoto"); } }
private void btnCreateRasterDrawing_Click(object sender, EventArgs e) { string fname = null; using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Filter = "(*.ldf)|*.ldf"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fname = dlg.FileName; } else { return; } } string ops = null; if (fname.EndsWith(".txt")) { ops = "ComponentID=0000000"; } IRasterDrawing drawing = new RasterDrawing(fname, _canvas, null, ops); drawing.LoadingSubscribers.Add(this); drawing.SelectedBandNos = new int[] { 1, 2, 3 }; IRasterLayer lyr = new RasterLayer(drawing); _canvas.LayerContainer.Layers.Add(lyr); _canvas.PrimaryDrawObject = drawing; _canvas.CurrentEnvelope = drawing.OriginalEnvelope; drawing.StartLoading((t, p) => { Text = p.ToString() + "/" + t.ToString(); }); _canvas.Refresh(enumRefreshType.All); _rasterLayer = lyr; //_canvas.OnEnvelopeChanged += new EventHandler(CanvasEnvelopeChanged); }
private async void Initialize() { // Create a new map. _myMapView.Map = new Map(BasemapStyle.ArcGISLightGray); // Get the GeoPackage path. string geoPackagePath = DataManager.GetDataFolder("68ec42517cdd439e81b036210483e8e7", "AuroraCO.gpkg"); try { // Open the GeoPackage. GeoPackage geoPackage = await GeoPackage.OpenAsync(geoPackagePath); // Read the raster images and get the first one. Raster gpkgRaster = geoPackage.GeoPackageRasters.FirstOrDefault(); // Make sure an image was found in the package. if (gpkgRaster == null) { return; } // Create a layer to show the raster. RasterLayer newLayer = new RasterLayer(gpkgRaster); await newLayer.LoadAsync(); // Set the viewpoint. await _myMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent)); // Add the image as a raster layer to the map (with default symbology). _myMapView.Map.OperationalLayers.Add(newLayer); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
// Skapar minstakostnadslager. public IRasterLayer createLeastCost(System.String destinationRaster, System.String outPath) { if (destinationRaster == "" || outPath == "") { MessageBox.Show("Check your rasters"); } else { Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; //gp.AddOutputsToMap = false; CostPath costPathTool = new CostPath(); costPathTool.in_cost_backlink_raster = backLink; costPathTool.in_cost_distance_raster = costDist; costPathTool.in_destination_data = dest; costPathTool.out_raster = outPath; IGeoProcessorResult geoProcessorResult = (IGeoProcessorResult)gp.Execute(costPathTool, null); leastCost = new RasterLayer(); leastCost.CreateFromFilePath(outPath); } return(leastCost); }
private async void Initialize() { // Create a map with a streets basemap. Map myMap = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); try { // Create a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Set the initial viewpoint for the map to the raster's full extent. myMap.InitialViewpoint = new Viewpoint(_rasterLayer.FullExtent); // Add the layer to the map. myMap.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = myMap; // Create the settings view controllers. _minMaxController = new MinMaxSettingsController(_rasterLayer); _percentClipController = new PercentClipSettingsController(_rasterLayer); _stdDevController = new StandardDeviationSettingsController(_rasterLayer); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
private async void Initialize() { // Define a new map with Wgs84 Spatial Reference. var map = new Map(BasemapType.Oceans, latitude: -34.1, longitude: 18.6, levelOfDetail: 9); // Get the file name for the raster. string filepath = DataManager.GetDataFolder("b5f977c78ec74b3a8857ca86d1d9b318", "SA_EVI_8Day_03May20.tif"); // Load the raster file. var raster = new Raster(filepath); // Initialize the raster layer. _rasterLayer = new RasterLayer(raster); // Add the raster layer to the map. map.OperationalLayers.Add(_rasterLayer); // Add map to the map view. MyMapView.Map = map; try { // Wait for the layer to load. await _rasterLayer.LoadAsync(); // Set the viewpoint. await MyMapView.SetViewpointGeometryAsync(_rasterLayer.FullExtent); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK"); } // Listen for mouse movement to start the identify operation. MyMapView.GeoViewTapped += MapTapped; }
private async void Initialize() { // Initialize the GUI controls appearance RendererTypes.Items.Add("Min Max"); RendererTypes.Items.Add("Percent Clip"); RendererTypes.Items.Add("Standard Deviation"); RendererTypes.SelectedIndex = 0; // Add an imagery basemap MyMapView.Map = new Map(Basemap.CreateImagery()); // Get the file name string filepath = GetRasterPath(); // Load the raster file Raster myRasterFile = new Raster(filepath); // Create the layer RasterLayer myRasterLayer = new RasterLayer(myRasterFile); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myRasterLayer); try { // Wait for the layer to load await myRasterLayer.LoadAsync(); // Set the viewpoint await MyMapView.SetViewpointGeometryAsync(myRasterLayer.FullExtent); } catch (Exception e) { await new MessageDialog(e.ToString(), "Error").ShowAsync(); } }
private void SelectRenderingRule(RenderingRuleInfo renderingRuleInfo) { // Create a new rendering rule from the rendering rule info. RenderingRule renderingRule = new RenderingRule(renderingRuleInfo); // Create a new image service raster. ImageServiceRaster imageServiceRaster = new ImageServiceRaster(_myUri) { // Set the image service raster's rendering rule to the rendering rule created earlier. RenderingRule = renderingRule }; // Create a new raster layer from the image service raster. RasterLayer rasterLayer = new RasterLayer(imageServiceRaster); // Clear the existing layer from the map. _myMapView.Map.OperationalLayers.Clear(); // Add the raster layer to the operational layers of the map view. _myMapView.Map.OperationalLayers.Add(rasterLayer); // Update the label. _selectionLabel.Text = $"Rule \"{renderingRuleInfo.Name}\" selected."; }
public void AddLayer(string layerpath) { IRasterLayer rasterLayer; rasterLayer = new RasterLayer(); rasterLayer.CreateFromFilePath(layerpath); if (frm.axTOCControl1.InvokeRequired)//如果调用控件的线程和创建控件的线程不是同一个则为true { while (!frm.axTOCControl1.IsHandleCreated) { //解决窗体关闭时出现“访问已释放句柄”的异常 if (frm.axTOCControl1.Disposing || frm.axTOCControl1.IsDisposed) { return; } } AddLayerdelegate d = new AddLayerdelegate(AddLayer); frm.axTOCControl1.Invoke(d, new object[] { layerpath }); } else { frm.mainMap.AddLayer(rasterLayer); } }
private void BtnOK_Click(object sender, EventArgs e) { IReclassOp reCla; reCla = new RasterReclassOp() as IReclassOp; //为分类着色用 IRemap pRemap; INumberRemap pSRemap; pSRemap = new NumberRemap() as INumberRemap; for (int i = 1; i <= Convert.ToInt32(DataGridFilterData.VisibleRowCount - 1); i++) { String str; //DataGridFilterData.ce str = DataGridFilterData[i - 1, 0].ToString(); float fvalue, tvalue; int p; p = str.LastIndexOf("~"); fvalue = Convert.ToSingle(str.Substring(0, p)); tvalue = Convert.ToSingle(str.Substring(p + 1, str.Length - p - 1)); pSRemap.MapRange(fvalue, tvalue, i); } // pSRemap.MapValueToNoData(-9999) pRemap = (IRemap)pSRemap; IGeoDataset pOutputRaster = null; try { pOutputRaster = reCla.ReclassByRemap((IGeoDataset)pRster, pRemap, true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } IRasterLayer pRlayer; pRlayer = new RasterLayer(); pRlayer.CreateFromRaster((IRaster)pOutputRaster); pRlayer.Name = Name + "Reclass"; IRaster ds; ds = (IRaster)pOutputRaster; IRasterLayer pla; pla = SetStretchRenderer(ds); IColorRamp pRamp; //获得色带 int index = imgCmbSingleClassify.SelectedIndex; pRamp = AlgorithmicColorRamp(index, DataGridFilterData.VisibleRowCount - 1); //分级色带渲染 SingleClassifyRender(pRlayer, DataGridFilterData.VisibleRowCount - 1, pRamp); FrmGISMain.mainMap.AddLayer(pRlayer, 0); //FrmGISMain.mainMap.AddLayer(pRlayer, 0); Oput(pRlayer); //Output(pRlayer); }
private void UpdateRendererButton_Clicked(object sender, EventArgs e) { // This function acquires the user selection of the stretch renderer from the table view // along with the parameters specified, then a stretch renderer is created and applied to // the raster layer. // Convert the input text to doubles and return if they're invalid. double input1; double input2; try { input1 = Convert.ToDouble(_inputParameter1.Text); input2 = Convert.ToDouble(_inputParameter2.Text); } catch (Exception ex) { new UIAlertView("alert", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show(); return; } // Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render. IEnumerable <double> gammaValues = new List <double>(); // Create a color ramp for the stretch renderer. ColorRamp colorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000); // Create the place holder for the stretch renderer. StretchRenderer stretchRenderer = null; switch (_rendererTypes.SelectedSegment) { case 0: // This section creates a stretch renderer based on a MinMaxStretchParameters. // TODO: Add you own logic to ensure that accurate min/max stretch values are used. try { // Create an IEnumerable from a list of double min stretch value doubles. IEnumerable <double> minValues = new List <double> { input1 }; // Create an IEnumerable from a list of double max stretch value doubles. IEnumerable <double> maxValues = new List <double> { input2 }; // Create a new MinMaxStretchParameters based on the user choice for min and max stretch values. MinMaxStretchParameters minMaxStretchParameters = new MinMaxStretchParameters(minValues, maxValues); // Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp. stretchRenderer = new StretchRenderer(minMaxStretchParameters, gammaValues, true, colorRamp); } catch (ArgumentException) { ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again."); return; } break; case 1: // This section creates a stretch renderer based on a PercentClipStretchParameters. // TODO: Add you own logic to ensure that accurate min/max percent clip values are used. try { // Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values. PercentClipStretchParameters percentClipStretchParameters = new PercentClipStretchParameters(input1, input2); // Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp. stretchRenderer = new StretchRenderer(percentClipStretchParameters, gammaValues, true, colorRamp); } catch (Exception) { ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again."); return; } break; case 2: // This section creates a stretch renderer based on a StandardDeviationStretchParameters. // TODO: Add you own logic to ensure that an accurate standard deviation value is used try { // Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value. StandardDeviationStretchParameters standardDeviationStretchParameters = new StandardDeviationStretchParameters(input1); // Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp. stretchRenderer = new StretchRenderer(standardDeviationStretchParameters, gammaValues, true, colorRamp); } catch (Exception) { ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again."); return; } break; } // Get the existing raster layer in the map. RasterLayer rasterLayer = (RasterLayer)_myMapView.Map.OperationalLayers[0]; // Apply the stretch renderer to the raster layer. rasterLayer.Renderer = stretchRenderer; }
private void btnok_Click(object sender, EventArgs e) { ESRI.ArcGIS.DataManagementTools.CreatePansharpenedRasterDataset cpr = new CreatePansharpenedRasterDataset(); string inraster = GetLayerList(quanse.Text); string inpanchromaticimage = GetLayerList(duoguangpu.Text); cpr.in_raster = inraster; cpr.in_panchromatic_image = inpanchromaticimage; cpr.out_raster_dataset = textbaocun.Text; cpr.red_channel = Convert.ToInt32(redboduan.Text.ToString()); cpr.green_channel = Convert.ToInt32(greenboduan.Text.ToString()); cpr.blue_channel = Convert.ToInt32(blueboduan.Text.ToString()); cpr.infrared_channel = 1; cpr.red_weight = Convert.ToDouble(redquanzhong.Text.ToString()); cpr.green_weight = Convert.ToDouble(greenquanzhong.Text.ToString()); cpr.blue_weight = Convert.ToDouble(bluequanzhong.Text.ToString()); cpr.infrared_weight = Convert.ToDouble(jinhongwaiquanzhong.Text.ToString()); cpr.pansharpening_type = ronghefangfa.Text; cpr.sensor = chuanganqi.Text; Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput = true; object obj = gp.Execute(cpr, null); IGeoProcessorResult gpResult = obj as IGeoProcessorResult; if (gpResult.Status == esriJobStatus.esriJobSucceeded) { DialogResult dr = MessageBox.Show("多波段合成操作成功"); if (dr == DialogResult.OK) { //结果添加到工作空间 if (addResult.Checked == true) { string fileFullName = textbaocun.Text; if (fileFullName == "") { return; } string filePathName = System.IO.Path.GetDirectoryName(fileFullName); string fileName = System.IO.Path.GetFileName(fileFullName); IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory(); //创建工作空间工厂 IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(filePathName, 0); //打开工作空间 IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace; //创建栅格工作空间 IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(fileName); //创建Dataset //影像金字塔创建与判断 IRasterPyramid2 pRasPymid = pRasterDataset as IRasterPyramid2; if (pRasPymid != null) { if (!(pRasPymid.Present)) { pRasPymid.Create();//创建金字塔 } } IRaster pRaster = pRasterDataset.CreateDefaultRaster(); IRasterLayer pRasterLayer = new RasterLayer(); pRasterLayer.CreateFromRaster(pRaster); ILayer pLayer = pRasterLayer as ILayer; axmapcontrol.AddLayer(pLayer, 0); } } } else { MessageBox.Show("多波段合成操作失败"); } }
private void OnUpdateRendererClicked(object sender, EventArgs e) { // This function acquires the user selection of the stretch renderer from the table view // along with the parameters specified, then a stretch renderer is created and applied to // the raster layer // Get the user choice for the raster stretch render UITableViewSource myUITableViewSource = _myRenderChoiceType.Source; TableSource myTableSource = (TableSource)myUITableViewSource; string myRendererTypeChoice; if (myTableSource.SelectedValue == null) { // If the user does not click on a choice in the table but just clicks the // button, the selected value will be null so use the initial // stretch renderer option myRendererTypeChoice = "Min Max"; } else { // The user clicked on an option in the table and thus the selected value // will contain a valid choice myRendererTypeChoice = myTableSource.SelectedValue; } // Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render IEnumerable <double> myGammaValues = new List <double>(); // Create a color ramp for the stretch renderer ColorRamp myColorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000); // Create the place holder for the stretch renderer StretchRenderer myStretchRenderer = null; switch (myRendererTypeChoice) { case "Min Max": // This section creates a stretch renderer based on a MinMaxStretchParameters // TODO: Add you own logic to ensure that accurate min/max stretch values are used // Create an IEnumerable from a list of double min stretch value doubles IEnumerable <double> myMinValues = new List <double> { Convert.ToDouble(_Input_Parameter1.Text) }; // Create an IEnumerable from a list of double max stretch value doubles IEnumerable <double> myMaxValues = new List <double> { Convert.ToDouble(_Input_Parameter2.Text) }; // Create a new MinMaxStretchParameters based on the user choice for min and max stretch values MinMaxStretchParameters myMinMaxStretchParameters = new MinMaxStretchParameters(myMinValues, myMaxValues); // Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myMinMaxStretchParameters, myGammaValues, true, myColorRamp); break; case "Percent Clip": // This section creates a stretch renderer based on a PercentClipStretchParameters // TODO: Add you own logic to ensure that accurate min/max percent clip values are used // Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values PercentClipStretchParameters myPercentClipStretchParameters = new PercentClipStretchParameters(Convert.ToDouble(_Input_Parameter1.Text), Convert.ToDouble(_Input_Parameter2.Text)); // Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myPercentClipStretchParameters, myGammaValues, true, myColorRamp); break; case "Standard Deviation": // This section creates a stretch renderer based on a StandardDeviationStretchParameters // TODO: Add you own logic to ensure that an accurate standard deviation value is used // Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value StandardDeviationStretchParameters myStandardDeviationStretchParameters = new StandardDeviationStretchParameters(Convert.ToDouble(_Input_Parameter1.Text)); // Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myStandardDeviationStretchParameters, myGammaValues, true, myColorRamp); break; } // Get the existing raster layer in the map RasterLayer myRasterLayer = (RasterLayer)_myMapView.Map.OperationalLayers[0]; // Apply the stretch renderer to the raster layer myRasterLayer.Renderer = myStretchRenderer; }
private void UpdateRendererButton_Clicked(object sender, EventArgs e) { try { // Define the RasterLayer that will be used to display in the map. RasterLayer rasterLayerForDisplayInMap; // Define the ColorRamp that will be used by the BlendRenderer. ColorRamp colorRamp; // Get the user choice for the ColorRamps. string selection = Enum.GetNames(typeof(PresetColorRampType))[_colorRampsPicker.SelectedSegment]; // Based on ColorRamp type chosen by the user, create a different // RasterLayer and define the appropriate ColorRamp option. if (selection == "None") { // The user chose not to use a specific ColorRamp, therefore // need to create a RasterLayer based on general imagery (i.e. Shasta.tif) // for display in the map and use null for the ColorRamp as one of the // parameters in the BlendRenderer constructor. // Load the raster file using a path on disk. Raster rasterImagery = new Raster(DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif")); // Create the raster layer from the raster. rasterLayerForDisplayInMap = new RasterLayer(rasterImagery); // Set up the ColorRamp as being null. colorRamp = null; } else { // The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight), // therefore create a RasterLayer based on an imagery with elevation // (i.e. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp // based on the user choice, translated into an Enumeration, as one of the parameters // in the BlendRenderer constructor. // Load the raster file using a path on disk. Raster rasterElevation = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif")); // Create the raster layer from the raster. rasterLayerForDisplayInMap = new RasterLayer(rasterElevation); // Create a ColorRamp based on the user choice, translated into an Enumeration. PresetColorRampType myPresetColorRampType = (PresetColorRampType)Enum.Parse(typeof(PresetColorRampType), selection); colorRamp = ColorRamp.Create(myPresetColorRampType, 256); } // Define the parameters used by the BlendRenderer constructor. Raster rasterForMakingBlendRenderer = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif")); IEnumerable <double> myOutputMinValues = new List <double> { 9 }; IEnumerable <double> myOutputMaxValues = new List <double> { 255 }; IEnumerable <double> mySourceMinValues = new List <double>(); IEnumerable <double> mySourceMaxValues = new List <double>(); IEnumerable <double> myNoDataValues = new List <double>(); IEnumerable <double> myGammas = new List <double>(); // Get the user choice for the SlopeType. string slopeSelection = Enum.GetNames(typeof(SlopeType))[_slopeTypesPicker.SelectedSegment]; SlopeType mySlopeType = (SlopeType)Enum.Parse(typeof(SlopeType), slopeSelection); rasterLayerForDisplayInMap.Renderer = new BlendRenderer( rasterForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source. myOutputMinValues, // outputMinValues - Output stretch values, one for each band. myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band. mySourceMinValues, // sourceMinValues - Input stretch values, one for each band. mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band. myNoDataValues, // noDataValues - NoData values, one for each band. myGammas, // gammas - Gamma adjustment. colorRamp, // colorRamp - ColorRamp object to use, could be null. _altitudeSlider.Value, // altitude - Altitude angle of the light source. _azimuthSlider.Value, // azimuth - Azimuth angle of the light source, measured clockwise from north. 1, // zfactor - Factor to convert z unit to x,y units, default is 1. mySlopeType, // slopeType - Slope Type. 1, // pixelSizeFactor - Pixel size factor, default is 1. 1, // pixelSizePower - Pixel size power value, default is 1. 8); // outputBitDepth - Output bit depth, default is 8-bit. // Set the new base map to be the RasterLayer with the BlendRenderer applied. _map.Basemap = new Basemap(rasterLayerForDisplayInMap); } catch (Exception ex) { Console.WriteLine(ex); } }
private void processLayer(XmlNode node) { XmlAttribute layerType = node.Attributes["type"]; LayerBase l; if (layerType != null && node.Attributes["type"].Value.ToString().Equals("raster")) { RasterLayer rl = new RasterLayer(); processBinding(node, rl); processRasterStyle(node, rl); processDataProvider(node, rl); processAppData(node, rl); l = rl; } else { FeatureLayer fl = new FeatureLayer(); if (node.Attributes["datasource"] != null) { #pragma warning disable 618 fl.DataSource = node.Attributes["datasource"].Value; fl.DataSourceType = (LayerDataSourceType)int.Parse(node.Attributes["datasource_type"].Value, CultureInfo.InvariantCulture); #pragma warning restore 618 } if (node.Attributes["dynamic_data_load"] != null) fl.AreFeaturesAutoLoadable = node.Attributes["dynamic_data_load"].Value == "1"; fl.FeaturesSelectable = node.Attributes["shapes_selectable"].Value == "1"; processTitleStyle(node, fl.TitleStyle); processPolygonStyle(node, fl.PolygonStyle); processPolylineStyle(node, fl.PolylineStyle); processPointStyle(node, fl.PointStyle); processIndicies(node, fl); processLegendSettings(node, fl); processAutoTitlesSettings(node, fl); processDataProvider(node, fl); processAppData(node, fl); l = fl; XmlNode layer_extensions = tryGetNodeByName(node.ChildNodes, "layer_extensions"); if (layer_extensions!= null) { foreach (XmlNode layerExtension in layer_extensions.ChildNodes) { if (layerExtension.Name == "layer_extension") processLayerExtension(layerExtension, fl); } } } l.Title = node.Attributes["title"].Value; l.Description = node.Attributes["description"].Value; if (node.Attributes["alias"] != null) l.Alias = node.Attributes["alias"].Value; l.Visible = node.Attributes["visible"].Value == "1"; if (node.Attributes["minimum_visible_scale"] != null) l.MinVisibleScale = double.Parse(node.Attributes["minimum_visible_scale"].Value, CultureInfo.InvariantCulture); if (node.Attributes["maximum_visible_scale"] != null) l.MaxVisibleScale = double.Parse(node.Attributes["maximum_visible_scale"].Value, CultureInfo.InvariantCulture); if (node.Attributes["controllable"] != null) l.Controllable = node.Attributes["controllable"].Value == "1"; if (node.Attributes["cacheable"] != null) l.Cacheable = node.Attributes["cacheable"].Value == "1"; _map.AddLayer(l); }
public bool AddRasterLayer(string fileLocation, string layerName, bool autoReproject = true, bool overwriteExistingReprojectedFiles = false) { Image img = new Image(); if (autoReproject) { if (!img.Open(fileLocation)) { Events.MapControl_Error errorFileNotOpen = new Events.MapControl_Error() { ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddRasterLayer", AxMapError = img.ErrorMsg[img.LastErrorCode] }; On_Error(errorFileNotOpen); } if (!IsRasterGoogleMercator(img)) { // Image is not WGS84, so use GdalWrap for reprojection string localData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (!System.IO.Directory.Exists(localData + "\\ResTBDesktop")) { System.IO.Directory.CreateDirectory(localData + "\\ResTBDesktop"); } string filename = Path.GetFileName(fileLocation); if (!Directory.Exists(localData + "\\ResTBDesktop\\temp")) { Directory.CreateDirectory(localData + "\\ResTBDesktop\\temp"); } // check if file already transformed if ((File.Exists(localData + "\\ResTBDesktop\\temp\\" + filename)) && (!overwriteExistingReprojectedFiles)) { } else { string fileLocationThreadSave = (string)fileLocation.Clone(); fileLocation = localData + "\\ResTBDesktop\\temp\\" + filename; RasterLayer r = new RasterLayer() { FileName = fileLocation, LayerType = LayerType.CustomLayerRaster, Name = layerName }; RasterProjectionWorker rpw = new RasterProjectionWorker(); rpw.MapControlTools = MapControlTools; rpw.MapControl_RasterReprojected += Callback_MapControl_RasterReprojected; reprojectThread = new Thread(() => rpw.Run(filename, fileLocationThreadSave, r)); Events.MapControl_BusyStateChange bc = new Events.MapControl_BusyStateChange(); bc.BusyState = Events.BusyState.BackgroundBusy; bc.KeyOfSender = Resources.MapControl_Busy_RasterReprojection; bc.Percent = 0; bc.Message = Resources.MapControl_Busy_StartRasterReprojection;; MapControlTools.On_BusyStateChange(bc); reprojectThread.Start(); return(false); } fileLocation = localData + "\\ResTBDesktop\\temp\\" + filename; } } if (img.Open(fileLocation)) { string proj = img.GetProjection(); int layerHandle = AxMap.AddLayer(img, true); if (layerHandle == -1) { Events.MapControl_Error imghandle_error = new Events.MapControl_Error() { ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddRasterLayer", AxMapError = new GlobalSettings().GdalLastErrorMsg }; On_Error(imghandle_error); return(false); } RasterLayer r = new RasterLayer() { FileName = fileLocation, Handle = layerHandle, LayerType = LayerType.CustomLayerRaster, Name = layerName }; MapControlTools.Layers.Add(r); MapControlTools.LayerHandlingTool.SetLayerPosition(r.Name, LayerMoveType.BOTTOM); Events.MapControl_LayerChange layerchange = new Events.MapControl_LayerChange() { LayerChangeReason = Events.LayerChangeReason.AddLayer, Layer = r }; On_LayerChange(layerchange); return(true); } Events.MapControl_Error error = new Events.MapControl_Error() { ErrorCode = Events.ErrorCodes.CouldNotLoadLayer, InMethod = "AddRasterLayer", AxMapError = img.ErrorMsg[img.LastErrorCode] }; On_Error(error); return(false); }
private async void Initialize() { // Create a map with a streets basemap. Map map = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); // Create a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); try { // Once the layer is loaded, enable the button to apply a new renderer. await _rasterLayer.LoadAsync(); ApplyRgbRendererButton.IsEnabled = true; // Create a viewpoint with the raster's full extent. Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent); // Set the initial viewpoint for the map. map.InitialViewpoint = fullRasterExtent; // Add the layer to the map. map.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. MyMapView.Map = map; // Add available stretch types to the combo box. StretchTypeComboBox.Items.Add("Min Max"); StretchTypeComboBox.Items.Add("Percent Clip"); StretchTypeComboBox.Items.Add("Standard Deviation"); // Select "Min Max" as the stretch type. StretchTypeComboBox.SelectedIndex = 0; // Create a range of values from 0-255. List <int> minMaxValues = Enumerable.Range(0, 256).ToList(); // Fill the min and max red combo boxes with the range and set default values. MinRedComboBox.ItemsSource = minMaxValues; MinRedComboBox.SelectedValue = 0; MaxRedComboBox.ItemsSource = minMaxValues; MaxRedComboBox.SelectedValue = 255; // Fill the min and max green combo boxes with the range and set default values. MinGreenComboBox.ItemsSource = minMaxValues; MinGreenComboBox.SelectedValue = 0; MaxGreenComboBox.ItemsSource = minMaxValues; MaxGreenComboBox.SelectedValue = 255; // Fill the min and max blue combo boxes with the range and set default values. MinBlueComboBox.ItemsSource = minMaxValues; MinBlueComboBox.SelectedValue = 0; MaxBlueComboBox.ItemsSource = minMaxValues; MaxBlueComboBox.SelectedValue = 255; // Fill the standard deviation factor combo box and set a default value. IEnumerable <int> wholeStdDevs = Enumerable.Range(1, 10); List <double> halfStdDevs = wholeStdDevs.Select(i => (double)i / 2).ToList(); StdDeviationFactorComboBox.ItemsSource = halfStdDevs; StdDeviationFactorComboBox.SelectedValue = 2.0; } catch (Exception e) { MessageBox.Show(e.ToString(), "Error"); } }
private async void Initialize() { // Create a new map centered on Aurora Colorado MyMapView.Map = new Map(BasemapType.Streets, 39.7294, -104.8319, 11); // Get the full path to the GeoPackage on the device string myGeoPackagePath = DataManager.GetDataFolder("68ec42517cdd439e81b036210483e8e7", "AuroraCO.gpkg"); // Open the GeoPackage GeoPackage myGeoPackage = await GeoPackage.OpenAsync(myGeoPackagePath); // Loop through each GeoPackageRaster foreach (GeoPackageRaster oneGeoPackageRaster in myGeoPackage.GeoPackageRasters) { // Create a RasterLayer from the GeoPackageRaster RasterLayer myRasterLayer = new RasterLayer(oneGeoPackageRaster) { // Set the opacity on the RasterLayer to partially visible Opacity = 0.55 }; // Load the RasterLayer - that way we can get to it's properties await myRasterLayer.LoadAsync(); // Create a string variable to hold the name of the RasterLayer for display // in the ListBox and the Dictionary - it will initially be an empty string string myRasterLayerName = ""; if (myRasterLayer.Name != "") { // We have a good name for the RasterLayer that came from // the RasterLayer.Name property myRasterLayerName = myRasterLayer.Name; } else if (oneGeoPackageRaster.Path.Split('/').Last() != "") { // We did not get a good name from the RasterLayer from the .Name // property, get the good name from the GeoPackageRaster.Path instead myRasterLayerName = oneGeoPackageRaster.Path.Split('/').Last(); } // Append the 'type of layer' to the myRasterLayerName string to display in the // ListBox and as the key for the Dictionary myRasterLayerName = myRasterLayerName + " - RasterLayer"; // Add the name of the RasterLayer and the RasterLayer itself into the Dictionary _nameToLayerDictionary[myRasterLayerName] = myRasterLayer; // Add the name of the RasterLayer to the ListBox of layers not in map LayersNotInTheMap.Items.Add(myRasterLayerName); } // Loop through each GeoPackageFeatureTable foreach (GeoPackageFeatureTable oneGeoPackageFeatureTable in myGeoPackage.GeoPackageFeatureTables) { // Create a FeatureLayer from the GeoPackageFeatureLayer FeatureLayer myFeatureLayer = new FeatureLayer(oneGeoPackageFeatureTable); // Load the FeatureLayer - that way we can get to it's properties await myFeatureLayer.LoadAsync(); // Create a string variable to hold the human-readable name of the FeatureLayer for // display in the ListBox and the Dictionary string myFeatureLayerName = myFeatureLayer.Name; // Append the 'type of layer' to the myFeatureLayerName string to display in the // ListBox and as the key for the Dictionary myFeatureLayerName = myFeatureLayerName + " - FeatureLayer"; // Add the name of the FeatureLayer and the FeatureLayer itself into the Dictionary _nameToLayerDictionary[myFeatureLayerName] = myFeatureLayer; // Add the name of the FeatureLayer to the ListBox of layers not in map LayersNotInTheMap.Items.Add(myFeatureLayerName); } }
private void addRasterStyleElement(RasterLayer layer, XmlDocument doc, XmlElement layerElement) { XmlElement rasterStyleElement = doc.CreateElement("raster_style"); layerElement.AppendChild(rasterStyleElement); addAttribute(doc, rasterStyleElement, "interpolation_mode", ((int)layer.Style.InterpolationMode).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm00", ((double)layer.Style.ColorAdjustmentMatrix.Matrix00).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm01", ((double)layer.Style.ColorAdjustmentMatrix.Matrix01).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm02", ((double)layer.Style.ColorAdjustmentMatrix.Matrix02).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm03", ((double)layer.Style.ColorAdjustmentMatrix.Matrix03).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm04", ((double)layer.Style.ColorAdjustmentMatrix.Matrix04).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm10", ((double)layer.Style.ColorAdjustmentMatrix.Matrix10).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm11", ((double)layer.Style.ColorAdjustmentMatrix.Matrix11).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm12", ((double)layer.Style.ColorAdjustmentMatrix.Matrix12).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm13", ((double)layer.Style.ColorAdjustmentMatrix.Matrix13).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm14", ((double)layer.Style.ColorAdjustmentMatrix.Matrix14).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm20", ((double)layer.Style.ColorAdjustmentMatrix.Matrix20).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm21", ((double)layer.Style.ColorAdjustmentMatrix.Matrix21).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm22", ((double)layer.Style.ColorAdjustmentMatrix.Matrix22).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm23", ((double)layer.Style.ColorAdjustmentMatrix.Matrix23).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm24", ((double)layer.Style.ColorAdjustmentMatrix.Matrix24).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm30", ((double)layer.Style.ColorAdjustmentMatrix.Matrix30).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm31", ((double)layer.Style.ColorAdjustmentMatrix.Matrix31).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm32", ((double)layer.Style.ColorAdjustmentMatrix.Matrix32).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm33", ((double)layer.Style.ColorAdjustmentMatrix.Matrix33).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm34", ((double)layer.Style.ColorAdjustmentMatrix.Matrix34).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm40", ((double)layer.Style.ColorAdjustmentMatrix.Matrix40).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm41", ((double)layer.Style.ColorAdjustmentMatrix.Matrix41).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm42", ((double)layer.Style.ColorAdjustmentMatrix.Matrix42).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm43", ((double)layer.Style.ColorAdjustmentMatrix.Matrix43).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, rasterStyleElement, "cm44", ((double)layer.Style.ColorAdjustmentMatrix.Matrix44).ToString(CultureInfo.InvariantCulture)); }
private void processBinding(XmlNode layerNode, RasterLayer l) { XmlNode binding = tryGetNodeByName(layerNode.ChildNodes, "binding"); if (binding != null) { if (l.Binding == null) l.Binding = new RasterLayer.RasterBinding(); l.Binding.RasterX = int.Parse(binding.Attributes["raster_x"].Value, CultureInfo.InvariantCulture); l.Binding.RasterY = int.Parse(binding.Attributes["raster_y"].Value, CultureInfo.InvariantCulture); l.Binding.PixelWidth = double.Parse(binding.Attributes["pixel_width"].Value, CultureInfo.InvariantCulture); l.Binding.PixelHeight = double.Parse(binding.Attributes["pixel_height"].Value, CultureInfo.InvariantCulture); l.Binding.MapPoint = Geometry.PlanimetryEnvironment.NewCoordinate( double.Parse(binding.Attributes["map_x"].Value, CultureInfo.InvariantCulture), double.Parse(binding.Attributes["map_y"].Value, CultureInfo.InvariantCulture)); } }
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(); }
protected override void OnClick() { string straboPath = Environment.GetEnvironmentVariable(ArcStrabo10Extension.EnvironmentVariableSTRABO_HOME, EnvironmentVariableTarget.User); string tessPath = Environment.GetEnvironmentVariable(ArcStrabo10Extension.EnvironmentVariableTESS_DATA, EnvironmentVariableTarget.User); if (ArcStrabo10Extension.PathSet == false) { if (String.IsNullOrEmpty(straboPath) == true) { MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoStraboHome); return; } if (String.IsNullOrEmpty(tessPath) == true) { MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoTess_Data); return; } ////Initialize directories bool Initialize_straboPath_Correct = ArcStrabo10Extension.initialize_straboPath_directories(straboPath); if (Initialize_straboPath_Correct == false) { MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoStraboHomeWritePermission); return; } ArcStrabo10Extension.PathSet = true; } #region Text Recognition ////Save Positive and Negative Layer and making GeoJason File ComboBoxLayerSelector layerNameCombo = ComboBoxLayerSelector.GetLayerNameComboBox(); ////Select correct raster map layer RasterLayer rasterlayer = new RasterLayer(); rasterlayer = ((RasterLayer)layerNameCombo.GetSelectedLayer()); string input_data_source_directory; try { input_data_source_directory = rasterlayer.FilePath; //input_data_source_directory = "B:\\Users\\akshay anand\\strabo\\strabo\\data\\text_extraction\\Opensource_Afghanistan_Kabul_City_Center\\"; } catch (Exception) { // Handle no input map error MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoInputMap, "Input Map Error", MessageBoxButtons.OK); return; } ////Select language from combo box in toolbar ComboBoxLanguageSelector languageNameCombo = ComboBoxLanguageSelector.GetLanguageNameComboBox(); string lng = languageNameCombo.Get_selected_language(); if (lng == null) { MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoInputLanguage, "Input Language Error", MessageBoxButtons.OK); return; } ////Set Log Directory Path Log.SetLogDir(ArcStrabo10Extension.Log_Path); Log.SetOutputDir(ArcStrabo10Extension.Log_Path); Log.WriteLine("MakingTextLabelGeoJsonFile Method Start SIMA"); IMap map = ArcMap.Document.FocusMap; ArcStraboObject arcStraboObject = new ArcStraboObject(); arcStraboObject.MakingTextLabelGeoJsonFile(ArcStrabo10Extension.Text_Result_Path); Log.WriteLine("MakingTextLabelGeoJsonFile Method Finish"); ////Run TextExtraction Layer from Strabo.core and load raster Layer Log.WriteLine("textLayerExtract Medthod Start SIMA"); arcStraboObject.textLayerExtract(input_data_source_directory, ArcStrabo10Extension.Text_Result_Path); Log.WriteLine("textLayerExtract Method Finish"); Log.WriteLine("AddRasterLayer Method Start SIMA"); arcStraboObject.AddRasterLayer(ArcStrabo10Extension.Text_Result_Path, ArcStrabo10Extension.TextLayerPNGFileName); Log.WriteLine("AddRasterLayer Method Finish"); ////Run TextIdentifier Method Log.WriteLine("textIndentification Method Start SIMA"); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; ///// Attempting to create cancel feature window //DialogResult result = MessageBox.Show("Text Recognition is running.", "Application Running", MessageBoxButtons.OKCancel); //if (result == DialogResult.Cancel) //{ // return; //} //else if (result == DialogResult.OK) arcStraboObject.textIndentification(ArcStrabo10Extension.Text_Result_Path + "\\", ArcStrabo10Extension.Intermediate_Result_Path + "\\", ArcStrabo10Extension.TextLayerPNGFileName); System.Windows.Forms.Cursor.Current = Cursors.Default; Log.WriteLine("textIndentification Method Finish"); ////OCR Part Log.WriteLine("ExtractTextToGEOJSON Method Start SANJUALI"); System.Windows.Forms.Cursor.Current = Cursors.AppStarting; //// Select language from combo box in toolbar // ComboBoxLanguageSelector languageNameCombo = ComboBoxLanguageSelector.GetLanguageNameComboBox(); // string lng = languageNameCombo.Get_selected_language(); if (lng == null) { MessageBox.Show(ArcStrabo10Extension.ErrorMsgNoInputLanguage, "Input Language Error", MessageBoxButtons.OK); return; } Strabo.Core.OCR.WrapperTesseract language = new Strabo.Core.OCR.WrapperTesseract(tessPath, lng); /// Strabo.Core.OCR.WrapperTesseract language = new Strabo.Core.OCR.WrapperTesseract(tessPath); language.ExtractTextToGEOJSON(ArcStrabo10Extension.Intermediate_Result_Path,ArcStrabo10Extension.Text_Result_Path,ArcStrabo10Extension.TesseractResultsJSONFileName); Log.WriteLine("ExtractTextToGEOJSON Method Finish"); System.Windows.Forms.Cursor.Current = Cursors.Default; ////Add Polygon of OCR Layer Log.WriteLine("CreateFeatureClassWithFields Method Start SIMA"); IWorkspace workspace = arcStraboObject.CreateShapefileWorkspace(ArcStrabo10Extension.Text_Result_Path); IFeatureWorkspace featureworkspace = (IFeatureWorkspace)workspace; string tesseDataPath = ArcStrabo10Extension.Text_Result_Path + "\\" + ArcStrabo10Extension.TesseractResultsJSONFileName; IFeatureClass featureClass = arcStraboObject.CreateFeatureClassWithFields(ArcStrabo10Extension.TextLayerOCRShapefile, featureworkspace, tesseDataPath); IFeatureLayer featureLayer = arcStraboObject.CreateFeatureLayer(featureClass); Log.WriteLine("CreateFeatureClassWithFields Method Finish"); Log.WriteLine("AddPolygon Method Start"); arcStraboObject.AddPolygon(featureLayer, featureworkspace, tesseDataPath); Log.WriteLine("AddPolygon Method Finish"); Log.ArchiveLog(); MessageBox.Show("Text recognition finished!", "Done", MessageBoxButtons.OK); #endregion }
public RasterReprojectCallback(RasterLayer r, MapControlTools mapControlTool) : base() { this.r = r; this.MapControlTool = mapControlTool; }
//Click to create suitability map private async void Map_Click(object sender, EventArgs e) { var mapView = MapView.Active; List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //using await instead of .wait() for asynchronous execution (Wait for the results) await QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath); myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum[k], 2)); } } } }); //t.Wait(); //For Showing Progress Window (Optional) var progDlgWS = new ProgressDialog("Weighted Sum Progress", "Cancel", 100, true); progDlgWS.Show(); var progSrc = new CancelableProgressorSource(progDlgWS); string weightedSumRaster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster"); var param_values = Geoprocessing.MakeValueArray(myinputs, weightedSumRaster); //use toolBoxNameAlias.toolName.Alias string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); //Uncomment below line if you want GP tool to open in Pro //Geoprocessing.OpenToolDialog(toolpath, param_values); progressLabel.Text = "Performing Weighted Sum, please wait..."; //Not adding weighted sum result to map since its intermediate result await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, new CancelableProgressorSource(progDlgWS).Progressor, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Weighted Sum processing complete. Reclassification started"; //Hide the progress once done. progDlgWS.Hide(); //----Use this if you want to see GP result messages---// //---The flow doesnt progress forward unless you close this box-----// //Geoprocessing.ShowMessageBox(wsresult.Messages, "GP Messages", //wsresult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default); //Creating a list string to store reclass values List <string> remap = new List <string>(); //Classifying into 3 classes, values can be modified as per user needs. remap.Add("0 0.6 1"); //Least Suitable remap.Add("0.6 0.8 2"); //Moderately Suitable remap.Add("0.8 1 3"); //Highly Suitable string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + "reclass0"); var reclassedRaster = Geoprocessing.MakeValueArray(weightedSumRaster, "VALUE", remap, output_raster2); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", reclassedRaster, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Completed. Check in TOC"; //Geoprocessing.OpenToolDialog("sa.Reclassify", reclassedRaster); }
private void addRasterbindingElement(RasterLayer layer, XmlDocument doc, XmlElement layerElement) { XmlElement bindingElement = doc.CreateElement("binding"); layerElement.AppendChild(bindingElement); addAttribute(doc, bindingElement, "raster_x", ((int)layer.Binding.RasterX).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, bindingElement, "raster_y", ((int)layer.Binding.RasterY).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, bindingElement, "map_x", ((double)layer.Binding.MapPoint.X).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, bindingElement, "map_y", ((double)layer.Binding.MapPoint.Y).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, bindingElement, "pixel_width", ((double)layer.Binding.PixelWidth).ToString(CultureInfo.InvariantCulture)); addAttribute(doc, bindingElement, "pixel_height", ((double)layer.Binding.PixelHeight).ToString(CultureInfo.InvariantCulture)); }
private async void Initialize() { // Get all the ColorRamp names from the PresetColorRampType Enumeration and put them // in an array of strings, then set the ComboBox.ItemSource to the array, and finally // select the first item in the ComboBox string[] myPresetColorRampTypes = System.Enum.GetNames(typeof(PresetColorRampType)); ColorRamps.ItemsSource = myPresetColorRampTypes; ColorRamps.SelectedIndex = 0; // Get all the SlopeType names from the SlopeType Enumeration and put them // in an array of strings, then set the ComboBox.ItemSource to the array, and finally // select the first item in the ComboBox string[] mySlopeTypes = System.Enum.GetNames(typeof(SlopeType)); SlopeTypes.ItemsSource = mySlopeTypes; SlopeTypes.SelectedIndex = 0; // Set the altitude slider min/max and initial value AltitudeSlider.Minimum = 0; AltitudeSlider.Maximum = 90; AltitudeSlider.Value = 45; // Set the azimuth slider min/max and initial value AzimuthSlider.Minimum = 0; AzimuthSlider.Maximum = 360; AzimuthSlider.Value = 180; // Load the raster file using a path on disk Raster myRasterImagery = new Raster(GetRasterPath_Imagery()); // Create the raster layer from the raster RasterLayer myRasterLayerImagery = new RasterLayer(myRasterImagery); // Create a new map using the raster layer as the base map Map myMap = new Map(new Basemap(myRasterLayerImagery)); try { // Wait for the layer to load - this enabled being able to obtain the extent information // of the raster layer await myRasterLayerImagery.LoadAsync(); // Create a new EnvelopeBuilder from the full extent of the raster layer EnvelopeBuilder myEnvelopBuilder = new EnvelopeBuilder(myRasterLayerImagery.FullExtent); // Zoom in the extent just a bit so that raster layer encompasses the entire viewable area of the map myEnvelopBuilder.Expand(0.75); // Set the viewpoint of the map to the EnvelopeBuilder's extent myMap.InitialViewpoint = new Viewpoint(myEnvelopBuilder.ToGeometry().Extent); // Add map to the map view MyMapView.Map = myMap; // Wait for the map to load await myMap.LoadAsync(); // Enable the 'Update Renderer' button now that the map has loaded UpdateRenderer.IsEnabled = true; } catch (Exception e) { await new MessageDialog(e.ToString(), "Error").ShowAsync(); } }
private async void Initialize() { // Create new map with the streets basemap Map myMap = new Map(Basemap.CreateStreets()); // Create a Uri to the image service raster Uri myUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NLCDLandCover2001/ImageServer"); // Create new image service raster from the Uri ImageServiceRaster myImageServiceRaster = new ImageServiceRaster(myUri); try { // Load the image service raster await myImageServiceRaster.LoadAsync(); // NOTE: This is the ASCII text for actual raw JSON string: // ======================================================== //{ // "raster_function_arguments": // { // "z_factor":{"double":25.0,"type":"Raster_function_variable"}, // "slope_type":{"raster_slope_type":"none","type":"Raster_function_variable"}, // "azimuth":{"double":315,"type":"Raster_function_variable"}, // "altitude":{"double":45,"type":"Raster_function_variable"}, // "type":"Raster_function_arguments", // "raster":{"name":"raster","is_raster":true,"type":"Raster_function_variable"}, // "nbits":{"int":8,"type":"Raster_function_variable"} // }, // "raster_function":{"type":"Hillshade_function"}, // "type":"Raster_function_template" //} // Define the JSON string needed for the raster function string theJSON_String = @"{ ""raster_function_arguments"": { ""z_factor"":{ ""double"":25.0,""type"":""Raster_function_variable""}, ""slope_type"":{ ""raster_slope_type"":""none"",""type"":""Raster_function_variable""}, ""azimuth"":{ ""double"":315,""type"":""Raster_function_variable""}, ""altitude"":{ ""double"":45,""type"":""Raster_function_variable""}, ""type"":""Raster_function_arguments"", ""raster"":{ ""name"":""raster"",""is_raster"":true,""type"":""Raster_function_variable""}, ""nbits"":{ ""int"":8,""type"":""Raster_function_variable""} }, ""raster_function"":{ ""type"":""Hillshade_function""}, ""type"":""Raster_function_template"" }"; // Create a raster function from the JSON string using the static/Shared method called: RasterFunction.FromJson(json as String) RasterFunction myRasterFunction = RasterFunction.FromJson(theJSON_String); // NOTE: Depending on your platform/device, you could have alternatively created the raster function via a JSON string that is contained in a // file on disk (ex: hillshade_simplified.json) via the constructor: Esri.ArcGISRuntime.Rasters.RasterFunction(path as String) // Get the raster function arguments RasterFunctionArguments myRasterFunctionArguments = myRasterFunction.Arguments; // Get the list of names from the raster function arguments IReadOnlyList <string> myRasterNames = myRasterFunctionArguments.GetRasterNames(); // Apply the first raster name and image service raster in the raster function arguments myRasterFunctionArguments.SetRaster(myRasterNames[0], myImageServiceRaster); // Create a new raster based on the raster function Raster myRaster = new Raster(myRasterFunction); // Create a new raster layer from the raster RasterLayer myRasterLayer = new RasterLayer(myRaster); // Add the raster layer to the maps layer collection myMap.Basemap.BaseLayers.Add(myRasterLayer); // Assign the map to the map view _myMapView.Map = myMap; // Get the service information (aka. metadata) about the image service raster ArcGISImageServiceInfo myArcGISImageServiceInfo = myImageServiceRaster.ServiceInfo; // Zoom the map to the extent of the image service raster (which also the extent of the raster layer) await _myMapView.SetViewpointGeometryAsync(myArcGISImageServiceInfo.FullExtent); // NOTE: The sample zooms to the extent of the ImageServiceRaster. Currently the ArcGIS Runtime does not // support zooming a RasterLayer out beyond 4 times it's published level of detail. The sample uses // MapView.SetViewpointCenterAsync() method to ensure the image shows when the app starts. You can see // the effect of the image service not showing when you zoom out to the full extent of the image and beyond. } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
private void processRasterStyle(XmlNode layerNode, RasterLayer l) { XmlNode rasterStyle = tryGetNodeByName(layerNode.ChildNodes, "raster_style"); if (rasterStyle != null) { l.Style.InterpolationMode = (InterpolationMode)int.Parse(rasterStyle.Attributes["interpolation_mode"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix00 = float.Parse(rasterStyle.Attributes["cm00"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix01 = float.Parse(rasterStyle.Attributes["cm01"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix02 = float.Parse(rasterStyle.Attributes["cm02"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix03 = float.Parse(rasterStyle.Attributes["cm03"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix04 = float.Parse(rasterStyle.Attributes["cm04"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix10 = float.Parse(rasterStyle.Attributes["cm10"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix11 = float.Parse(rasterStyle.Attributes["cm11"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix12 = float.Parse(rasterStyle.Attributes["cm12"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix13 = float.Parse(rasterStyle.Attributes["cm13"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix14 = float.Parse(rasterStyle.Attributes["cm14"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix20 = float.Parse(rasterStyle.Attributes["cm20"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix21 = float.Parse(rasterStyle.Attributes["cm21"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix22 = float.Parse(rasterStyle.Attributes["cm22"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix23 = float.Parse(rasterStyle.Attributes["cm23"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix24 = float.Parse(rasterStyle.Attributes["cm24"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix30 = float.Parse(rasterStyle.Attributes["cm30"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix31 = float.Parse(rasterStyle.Attributes["cm31"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix32 = float.Parse(rasterStyle.Attributes["cm32"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix33 = float.Parse(rasterStyle.Attributes["cm33"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix34 = float.Parse(rasterStyle.Attributes["cm34"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix40 = float.Parse(rasterStyle.Attributes["cm40"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix41 = float.Parse(rasterStyle.Attributes["cm41"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix42 = float.Parse(rasterStyle.Attributes["cm42"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix43 = float.Parse(rasterStyle.Attributes["cm43"].Value, CultureInfo.InvariantCulture); l.Style.ColorAdjustmentMatrix.Matrix44 = float.Parse(rasterStyle.Attributes["cm44"].Value, CultureInfo.InvariantCulture); } }
async public Task <IRasterLayer> NextRasterLayer() { if (_cursor == null || _layer == null) { return(null); } try { while (true) { IFeature feature = await _cursor.NextFeature(); if (feature == null) { return(null); } IRasterLayer rLayer = null; double cell = Math.Max((double)feature["CELLX"], (double)feature["CELLY"]); int levels = (int)feature["LEVELS"], level = 0; if ((bool)feature["MANAGED"] && _layer._imageSpaceType == SqlFDBImageCatalogClass.ImageSpaceType.Database) { for (int l = 0; l < levels; l++) { if (cell * Math.Pow(2, l) < _pix) { level = l + 1; } else { break; } } if (level == 0 && levels > 0) { level = 1; } DataTable tab = await _layer._fdb.Select("ID,SHAPE", _layer._dsname + "_IMAGE_DATA", "IMAGE_ID=" + feature.OID + " AND LEV=" + level); if (tab == null) { continue; } foreach (DataRow row in tab.Rows) { byte[] obj = (byte[])row["SHAPE"]; BinaryReader r = new BinaryReader(new MemoryStream()); r.BaseStream.Write((byte[])obj, 0, ((byte[])obj).Length); r.BaseStream.Position = 0; Polygon polygon = new Polygon(); polygon.Deserialize(r, new GeometryDef(geometryType.Polygon, null, true)); r.Close(); if (gView.Framework.SpatialAlgorithms.Algorithm.IntersectBox(polygon, _dispEnvelope)) { SqlFDBImageDatasetImageClass rClass = new SqlFDBImageDatasetImageClass(_layer._fdb, _layer._dsname, (int)row["ID"], polygon); rLayer = new RasterLayer(rClass); rLayer.InterpolationMethod = _layer.InterpolationMethod; if (rClass.SpatialReference == null) { rClass.SpatialReference = _layer._sRef; } } } } else if (!(bool)feature["MANAGED"]) { if (feature["RF_PROVIDER"] == null || feature["RF_PROVIDER"] == DBNull.Value) { gView.DataSources.Raster.File.RasterFileDataset rDataset = new gView.DataSources.Raster.File.RasterFileDataset(); rLayer = rDataset.AddRasterFile((string)feature["PATH"], feature.Shape as IPolygon); } else { IRasterFileDataset rDataset = _layer._compMan.CreateInstance(new Guid(feature["RF_PROVIDER"].ToString())) as IRasterFileDataset; if (rDataset == null) { continue; } rLayer = rDataset.AddRasterFile((string)feature["PATH"], feature.Shape as IPolygon); } if (rLayer != null && rLayer.RasterClass != null) { rLayer.InterpolationMethod = _layer.InterpolationMethod; if (rLayer.RasterClass.SpatialReference == null) { rLayer.RasterClass.SpatialReference = _layer._sRef; } } } if (rLayer != null) { if (rLayer.Class is IGridClass) { IGridClass gridClass = (IGridClass)rLayer.Class; gridClass.ColorClasses = _layer.ColorClasses; gridClass.UseHillShade = _layer.UseHillShade; gridClass.HillShadeVector = _layer.HillShadeVector; gridClass.UseIgnoreDataValue = _layer.UseIgnoreDataValue; gridClass.IgnoreDataValue = _layer.IgnoreDataValue; gridClass.RenderRawGridValues = _layer.RenderRawGridValues; } return(rLayer); } } } catch { } return(null); }
public static ILayer AddToMap(FileSystemDataset dataset, string sLayerName, IGroupLayer pGroupLayer, List <string> precedingLayers, FileInfo fiSymbologyLayerFile = null, bool bAddToMapIfPresent = false, short transparency = 0, string definition_query = "") { if (!dataset.Exists) { return(null); } // Only add if it doesn't exist already ILayer pResultLayer = GetLayerBySource(dataset.Path); if ((pResultLayer is ILayer && string.Compare(pResultLayer.Name, sLayerName, true) == 0) && !bAddToMapIfPresent) { return(pResultLayer); } // Confirm that the symbology layer file exists if (fiSymbologyLayerFile != null && !fiSymbologyLayerFile.Exists) { Exception ex = new Exception("A symbology layer file was provided, but the file does not exist"); ex.Data["Data Source"] = dataset.Path.FullName; ex.Data["Layer file"] = fiSymbologyLayerFile.FullName; throw ex; } IWorkspace pWorkspace = GetWorkspace(dataset); switch (dataset.WorkspaceType) { case FileSystemDataset.GISDataStorageTypes.RasterFile: IRasterDataset pRDS = ((IRasterWorkspace)pWorkspace).OpenRasterDataset(Path.GetFileName(dataset.Path.FullName)); IRasterLayer pRLResult = new RasterLayer(); pRLResult.CreateFromDataset(pRDS); pResultLayer = pRLResult; break; case FileSystemDataset.GISDataStorageTypes.CAD: string sFile = Path.GetFileName(Path.GetDirectoryName(dataset.Path.FullName)); string sFC = sFile + ":" + Path.GetFileName(dataset.Path.FullName); IFeatureClass pFC = ((IFeatureWorkspace)pWorkspace).OpenFeatureClass(sFC); pResultLayer = new FeatureLayer(); ((IFeatureLayer)pResultLayer).FeatureClass = pFC; break; case FileSystemDataset.GISDataStorageTypes.ShapeFile: IFeatureWorkspace pWS = (IFeatureWorkspace)ArcMapUtilities.GetWorkspace(dataset); IFeatureClass pShapeFile = pWS.OpenFeatureClass(Path.GetFileNameWithoutExtension(dataset.Path.FullName)); pResultLayer = new FeatureLayer(); ((IFeatureLayer)pResultLayer).FeatureClass = pShapeFile; break; case FileSystemDataset.GISDataStorageTypes.TIN: ITin pTIN = ((ITinWorkspace)pWorkspace).OpenTin(System.IO.Path.GetFileName(dataset.Path.FullName)); pResultLayer = new TinLayer(); ((ITinLayer)pResultLayer).Dataset = pTIN; pResultLayer.Name = dataset.Name; break; case FileSystemDataset.GISDataStorageTypes.GeoPackage: IFeatureWorkspace pGPKGWS = (IFeatureWorkspace)ArcMapUtilities.GetWorkspace(dataset); IFeatureClass pGPKGFC = pGPKGWS.OpenFeatureClass(System.IO.Path.GetFileName(dataset.Path.FullName)); pResultLayer = new FeatureLayer(); ((IFeatureLayer)pResultLayer).FeatureClass = pGPKGFC; break; default: Exception ex = new Exception("Unhandled GIS dataset type"); ex.Data["FullPath Path"] = dataset.Path.FullName; ex.Data["Storage Type"] = dataset.WorkspaceType.ToString(); throw ex; } if (!string.IsNullOrEmpty(sLayerName)) { pResultLayer.Name = sLayerName; } try { ApplySymbology(pResultLayer, fiSymbologyLayerFile); } catch (Exception ex) { if (ex.Message.ToLower().Contains("symbology")) { System.Diagnostics.Debug.Print(ex.Message); // DO Nothing } else { throw; } } try { if (pResultLayer is IFeatureLayer && !string.IsNullOrEmpty(definition_query)) { ApplyDefinitionquery((IFeatureLayer)pResultLayer, definition_query); } } catch (Exception ex) { if (ex.Message.ToLower().Contains("symbology")) { System.Diagnostics.Debug.Print(ex.Message); // DO Nothing } else { throw; } } if (transparency > 0) { ILayerEffects pLayerEffects = (ILayerEffects)pResultLayer; pLayerEffects.Transparency = transparency; } if (pGroupLayer == null) { ((IMapLayers)ArcMap.Document.FocusMap).InsertLayer(pResultLayer, false, 0); } else { int layerIndex = 0; foreach (string name in precedingLayers) { // Try and find the preceding layer already in the hierarchy ICompositeLayer pCompositeLayer = (ICompositeLayer)pGroupLayer; for (int i = 0; i <= pCompositeLayer.Count - 1; i++) { if (string.Compare(pCompositeLayer.Layer[i].Name, name, true) == 0) { layerIndex++; } } } ((IMapLayers)ArcMap.Document.FocusMap).InsertLayerInGroup(pGroupLayer, pResultLayer, false, layerIndex); } ArcMap.Document.UpdateContents(); ArcMap.Document.ActiveView.Refresh(); ArcMap.Document.CurrentContentsView.Refresh(null); return(pResultLayer); }
private async void OnUpdateRendererClicked(object sender, RoutedEventArgs e) { // Convert the text to doubles and return if they're invalid. double input1; double input2; try { input1 = Convert.ToDouble(FirstParameterInput.Text); input2 = Convert.ToDouble(SecondParameterInput.Text); } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); return; } // Get the user choice for the raster stretch render string myRendererTypeChoice = RendererTypes.SelectedValue.ToString(); // Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render IEnumerable <double> myGammaValues = new List <double>(); // Create a color ramp for the stretch renderer ColorRamp myColorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000); // Create the place holder for the stretch renderer StretchRenderer myStretchRenderer = null; switch (myRendererTypeChoice) { case "Min Max": // This section creates a stretch renderer based on a MinMaxStretchParameters // TODO: Add you own logic to ensure that accurate min/max stretch values are used // Create an IEnumerable from a list of double min stretch value doubles IEnumerable <double> myMinValues = new List <double> { input1 }; // Create an IEnumerable from a list of double max stretch value doubles IEnumerable <double> myMaxValues = new List <double> { input2 }; // Create a new MinMaxStretchParameters based on the user choice for min and max stretch values MinMaxStretchParameters myMinMaxStretchParameters = new MinMaxStretchParameters(myMinValues, myMaxValues); // Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myMinMaxStretchParameters, myGammaValues, true, myColorRamp); break; case "Percent Clip": // This section creates a stretch renderer based on a PercentClipStretchParameters // TODO: Add you own logic to ensure that accurate min/max percent clip values are used // Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values PercentClipStretchParameters myPercentClipStretchParameters = new PercentClipStretchParameters(input1, input2); // Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myPercentClipStretchParameters, myGammaValues, true, myColorRamp); break; case "Standard Deviation": // This section creates a stretch renderer based on a StandardDeviationStretchParameters // TODO: Add you own logic to ensure that an accurate standard deviation value is used // Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value StandardDeviationStretchParameters myStandardDeviationStretchParameters = new StandardDeviationStretchParameters(input1); // Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp myStretchRenderer = new StretchRenderer(myStandardDeviationStretchParameters, myGammaValues, true, myColorRamp); break; } // Get the existing raster layer in the map RasterLayer myRasterLayer = (RasterLayer)MyMapView.Map.OperationalLayers[0]; // Apply the stretch renderer to the raster layer myRasterLayer.Renderer = myStretchRenderer; }
/// <summary> /// Add Raster Layer for the result of Extract textlayer /// </summary> /// <param name="path"></param> /// <param name="fileName"></param> public void AddRasterLayer(string path, string fileName) { IMap map = ArcMap.Document.FocusMap; try { IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory(); IRasterWorkspace rasterWorkspace = (ESRI.ArcGIS.DataSourcesRaster.IRasterWorkspace)(workspaceFactory.OpenFromFile(path, 0)); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName); IGeoDataset geoDataset = (ESRI.ArcGIS.Geodatabase.IGeoDataset)rasterDataset; // Create a raster for viewing IRasterLayer rasterLayer = new RasterLayer(); rasterLayer.CreateFromDataset(rasterDataset); // Add the raster to the map map.AddLayer(rasterLayer); } catch (System.Exception ex) { Log.WriteLine("AddRasterLayer: " + ex.Message); } }
private async void sensitivity_Click(object sender, EventArgs e) { if ((combo1.SelectedIndex == -1) || (combo2.SelectedIndex == -1)) { MessageBox.Show("Cannot Perform SA unless criteria and simulations are selected"); return; } Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "csv file (*.csv)|*.csv|txt file (*.txt)|*.txt|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.OverwritePrompt = true; saveFileDialog1.AddExtension = true; saveFileDialog1.InitialDirectory = @"D:\"; saveFileDialog1.Title = "Save your Weights"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { myStream.Close(); } } else if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) { MessageBox.Show("Save your csv file"); } string fp = saveFileDialog1.FileName; // Defining new array rowSum1 with length as rowSum double[] rowSum1 = new double[rowSum.Length]; for (int i = -Convert.ToInt16(combo2.SelectedItem) / 2; i <= Convert.ToInt16(combo2.SelectedItem) / 2; i++) { //Copy contents of rowSum to rowSum1 starting from 0 rowSum.CopyTo(rowSum1, 0); if (i == 0) { continue; } for (int j = 0; j < combo1.Items.Count; j++) { //Positive Increment if (i > 0) { rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i); if (j != combo1.SelectedIndex) { System.Diagnostics.Debug.WriteLine(i); rowSum1[j] = rowSum1[j] * (1 - 0.01 * i); } } //Negative increment else { rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i); if (j != combo1.SelectedIndex) { System.Diagnostics.Debug.WriteLine(i); rowSum1[j] = rowSum1[j] * (1 - 0.01 * i); } } //Skip iteration when i=0 } // Writing to a csv file string delimiter = ","; int length = rowSum1.Length; //using (TextWriter writer = File.CreateText(filepath)) using (TextWriter writer = File.AppendText(fp)) //StringBuilder csv = new StringBuilder(); { if (i == -Convert.ToInt16(combo2.SelectedItem) / 2) { writer.Write(string.Join(delimiter, "% Change", "\t")); for (int a = 0; a < combo1.Items.Count; a++) { writer.Write(string.Join(delimiter, combo1.Items[a], "\t")); } } writer.Write("\n"); writer.Write(string.Join(delimiter, i, "\t")); for (int index = 0; index < length; index++) { writer.Write(string.Join(delimiter, Math.Round(rowSum1[index], 3), "\t")); } } List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //Geoprocessing starts here await QueuedTask.Run(() => // Task t = QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers in Map View //System.Diagnostics.Debug.WriteLine(test.Nodes[k].Tag.ToString()); for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath);//getting path System.Diagnostics.Debug.WriteLine(rlyr.Name); System.Diagnostics.Debug.WriteLine(paths); // adding paths to input array, value and weights myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum1[k], 3)); System.Diagnostics.Debug.WriteLine(rowSum1); } } } }); //t.Wait(); System.Diagnostics.Debug.WriteLine(i); if (i < 0) { string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "down"); System.Diagnostics.Debug.WriteLine(output_raster); var param_values = Geoprocessing.MakeValueArray(myinputs, output_raster); string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None); progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % decrease"; List <string> remap = new List <string>(); remap.Add("0 0.6 1"); remap.Add("0.6 0.8 2"); remap.Add("0.8 1 3"); string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "downreclass"); var kufli = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2); //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % decrease. Check in TOC"; } else { string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + i + "up"); System.Diagnostics.Debug.WriteLine(output_raster); var param_values = Geoprocessing.MakeValueArray(myinputs, output_raster); string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None); progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % increase"; List <string> remap = new List <string>(); remap.Add("0 0.6 1"); remap.Add("0.6 0.8 2"); remap.Add("0.8 1 3"); string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "upreclass"); var kufli = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2); //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % increase. Check in TOC"; } foreach (var Item in rowSum1) { System.Diagnostics.Debug.WriteLine(Item.ToString()); } // Clear the array so that new values will be populated based on original Array.Clear(rowSum1, 0, rowSum1.Length); //Clear inputs myinputs.Clear(); } }
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(); }
private void OnUpdateRendererClicked(object sender, RoutedEventArgs e) { // Define the RasterLayer that will be used to display in the map RasterLayer rasterLayer_ForDisplayInMap; // Define the ColorRamp that will be used by the BlendRenderer ColorRamp myColorRamp; // Based on ColorRamp type chosen by the user, create a different // RasterLayer and define the appropriate ColorRamp option if (ColorRamps.SelectedValue.ToString() == "None") { // The user chose not to use a specific ColorRamp, therefore // need to create a RasterLayer based on general imagery (ie. Shasta.tif) // for display in the map and use null for the ColorRamp as one of the // parameters in the BlendRenderer constructor // Load the raster file using a path on disk Raster raster_Imagery = new Raster(GetRasterPath_Imagery()); // Create the raster layer from the raster rasterLayer_ForDisplayInMap = new RasterLayer(raster_Imagery); // Set up the ColorRamp as being null myColorRamp = null; } else { // The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight), // therefore create a RasterLayer based on an imagery with elevation // (ie. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp // based on the user choice, translated into an Enumeration, as one of the parameters // in the BlendRenderer constructor // Load the raster file using a path on disk Raster raster_Elevation = new Raster(GetRasterPath_Elevation()); // Create the raster layer from the raster rasterLayer_ForDisplayInMap = new RasterLayer(raster_Elevation); // Create a ColorRamp based on the user choice, translated into an Enumeration PresetColorRampType myPresetColorRampType = (PresetColorRampType)Enum.Parse(typeof(PresetColorRampType), ColorRamps.SelectedValue.ToString()); myColorRamp = ColorRamp.Create(myPresetColorRampType, 256); } // Define the parameters used by the BlendRenderer constructor Raster raster_ForMakingBlendRenderer = new Raster(GetRasterPath_Elevation()); IEnumerable <double> myOutputMinValues = new List <double> { 9 }; IEnumerable <double> myOutputMaxValues = new List <double> { 255 }; IEnumerable <double> mySourceMinValues = new List <double>(); IEnumerable <double> mySourceMaxValues = new List <double>(); IEnumerable <double> myNoDataValues = new List <double>(); IEnumerable <double> myGammas = new List <double>(); SlopeType mySlopeType = (SlopeType)Enum.Parse(typeof(SlopeType), SlopeTypes.SelectedValue.ToString()); BlendRenderer myBlendRenderer = new BlendRenderer( raster_ForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source myOutputMinValues, // outputMinValues - Output stretch values, one for each band myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band mySourceMinValues, // sourceMinValues - Input stretch values, one for each band mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band myNoDataValues, // noDataValues - NoData values, one for each band myGammas, // gammas - Gamma adjustment myColorRamp, // colorRamp - ColorRamp object to use, could be null Altitude_Slider.Value, // altitude - Altitude angle of the light source Azimuth_Slider.Value, // azimuth - Azimuth angle of the light source, measured clockwise from north 1, // zfactor - Factor to convert z unit to x,y units, default is 1 mySlopeType, // slopeType - Slope Type 1, // pixelSizeFactor - Pixel size factor, default is 1 1, // pixelSizePower - Pixel size power value, default is 1 8); // outputBitDepth - Output bit depth, default is 8-bi // Set the RasterLayer.Renderer to be the BlendRenderer rasterLayer_ForDisplayInMap.Renderer = myBlendRenderer; // Set the new base map to be the RasterLayer with the BlendRenderer applied MyMapView.Map.Basemap = new Basemap(rasterLayer_ForDisplayInMap); }
protected override void OnClick() { string straboPath = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableSTRABO_HOME, EnvironmentVariableTarget.User); string tessPath = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableTESS_DATA, EnvironmentVariableTarget.User); if (ArcStrabo2Extension.PathSet == false) { if (String.IsNullOrEmpty(straboPath) == true) { MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHome); return; } if (String.IsNullOrEmpty(tessPath) == true) { MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoTess_Data); return; } bool Initialize_straboPath_Correct = ArcStrabo2Extension.initialize_straboPath_directories(straboPath); if (Initialize_straboPath_Correct == false) { MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHomeWritePermission); return; } ArcStrabo2Extension.PathSet = true; } // // TODO: Sample code showing how to access button host // ArcMap.Application.CurrentTool = null; ComboBoxLayerSelector layerNameCombo = ComboBoxLayerSelector.GetLayerNameComboBox(); RasterLayer rasterlayer = new RasterLayer(); rasterlayer = ((RasterLayer)layerNameCombo.GetSelectedLayer()); //raster.Raster //RasterLayer raster2 = new RasterLayer(); //raster2.CreateFromRaster(raster.Raster); //IMap map = ArcMap.Document.FocusMap; //map.AddLayer((ILayer)raster2); //MessageBox.Show(layerNameCombo.selected_layer_name + " " + raster2.RowCount + " " + raster2.ColumnCount + " " + raster2.BandCount); ColorSegmentationWorker cs = new ColorSegmentationWorker(); try { IRaster2 iraster2 = rasterlayer.Raster as IRaster2; string[] bitmap_fns = cs.Apply(System.IO.Path.GetDirectoryName(iraster2.RasterDataset.CompleteName) + "\\", ArcStrabo2Extension.Text_Result_Path + "\\", System.IO.Path.GetFileName(iraster2.RasterDataset.CompleteName)); IMap map = ArcMap.Document.FocusMap; foreach (string path in bitmap_fns) { //RasterDataset rds = new RasterDataset(); //rds.OpenFromFile(path); RasterLayer rasterlayer2 = new RasterLayer(); rasterlayer2.CreateFromFilePath(path); map.AddLayer(rasterlayer2); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }