/// <summary> /// Open a Raster Dataset given a folder and a dataset name. /// </summary> /// <param name="folder">Full path to the folder containing the raster dataset.</param> /// <param name="name">Name of the raster dataset to open.</param> /// <returns></returns> public static RasterDataset OpenRasterDataset(string folder, string name) { // Create a new raster dataset which is set to null RasterDataset rasterDatasetToOpen = null; try { // Create a new file system connection path to open raster datasets using the folder path. FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(folder), FileSystemDatastoreType.Raster); // Create a new file system data store for the connection path created above. FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath); // Open the raster dataset. rasterDatasetToOpen = dataStore.OpenDataset <RasterDataset>(name); // Check if it is not null. If it is show a message box with the appropriate message. if (rasterDatasetToOpen == null) { MessageBox.Show("Failed to open raster dataset: " + name); } } catch (Exception exc) { // If an exception occurs, show a message box with the appropriate message. MessageBox.Show("Exception caught in OpenRasterDataset for raster: " + name + exc.Message); } return(rasterDatasetToOpen); }
/// <summary> /// Write results to a rester. /// </summary> /// <param name="raster">DEM raster</param> /// <param name="outputDataStore">Output datastore</param> /// <param name="result">Elevation map with resuluts</param> private void WriteToRaster(Raster raster, FileSystemDatastore outputDataStore, GeoMap result) { raster.SetNoDataValue(0); raster.SetPixelType(RasterPixelType.DOUBLE); RasterDataset resultRasterDataset = raster.SaveAs(tmpRasterName, outputDataStore, rasterFormat); GarbageHelper.Instance.AddGarbage(Path.Combine(outputFolder, tmpRasterName)); Raster resultRaster = resultRasterDataset.CreateRaster(new int[1] { 0 }); resultRaster.Refresh(); if (!resultRaster.CanEdit()) { MessageBox.Show("Cannot write to raster", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); return; } PixelBlock pixelBlock = resultRaster.CreatePixelBlock(resultRaster.GetWidth(), resultRaster.GetHeight()); resultRaster.Read(0, 0, pixelBlock); pixelBlock.Clear(0); Array pixel = new double[resultRaster.GetWidth(), resultRaster.GetHeight()]; pixelBlock.SetPixelData(0, result.Transpose()); resultRaster.Write(0, 0, pixelBlock); resultRaster.Refresh(); resultRaster.SaveAs(SettingsManager.Instance.CurrentSettings.OutputFilename, outputDataStore, rasterFormat); }
public static async Task DisplayRasterWithSymbolAsync(Uri rasterUri, string displayName, string styleCategory, string styleName, string fieldName, int transparency, bool isVisible) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (rasterUri.IsFile) { strFileName = System.IO.Path.GetFileName(rasterUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(rasterUri.LocalPath); } // Open the requested raster so we know it exists; return if it doesn't await QueuedTask.Run(async() => { RasterDataset rDataset = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. try { rDataset = geodatabase.OpenDataset <RasterDataset>(strFileName); } catch (GeodatabaseTableException e) { Debug.WriteLine("DisplayRasterWithSymbolAsync: Unable to open raster " + strFileName); Debug.WriteLine("DisplayRasterWithSymbolAsync: " + e.Message); return; } } RasterLayer rasterLayer = null; // Create the raster layer on the active map await QueuedTask.Run(() => { rasterLayer = (RasterLayer)LayerFactory.Instance.CreateLayer(rasterUri, MapView.Active.Map); }); // Set raster layer transparency and name if (rasterLayer != null) { rasterLayer.SetTransparency(transparency); rasterLayer.SetName(displayName); rasterLayer.SetVisibility(isVisible); // Create and deploy the unique values renderer await MapTools.SetToUniqueValueColorizer(displayName, styleCategory, styleName, fieldName); } }); }
public static async Task <double> GetCellSizeAsync(Uri gdbUri, string rasterName) { double cellSize = 0.0F; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (RasterDataset rasterDataset = geodatabase.OpenDataset <RasterDataset>(rasterName)) { RasterBandDefinition bandDefinition = rasterDataset.GetBand(0).GetDefinition(); Tuple <double, double> tupleSize = bandDefinition.GetMeanCellSize(); cellSize = (tupleSize.Item1 + tupleSize.Item2) / 2; } }); return(cellSize); }
public static Task <Envelope> GetRasterExtent(string path) { Task <Envelope> task = QueuedTask.Run(() => { string directory = System.IO.Path.GetDirectoryName(path); string fileName = System.IO.Path.GetFileName(path); FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(directory), FileSystemDatastoreType.Raster); FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath); RasterDataset fileRasterDataset = dataStore.OpenDataset <RasterDataset>(fileName); Raster raster = fileRasterDataset.CreateFullRaster(); Envelope env = raster.GetExtent(); return(env); }); return(task); }
private Raster OpenRasterFromDataset(string path, string rasterDatasetFileName) { Raster raster; FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new Uri(path), FileSystemDatastoreType.Raster); using (FileSystemDatastore datastore = new FileSystemDatastore(connectionPath)) { using (RasterDataset rasterDataset = datastore.OpenDataset <RasterDataset>(rasterDatasetFileName)) { // Create a full raster from the raster dataset. raster = rasterDataset.CreateFullRaster(); rasterDataset.Dispose(); } datastore.Dispose(); } return(raster); }
public static async Task DisplayRasterAsync(Uri rasterUri, string displayName, int transparency) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (rasterUri.IsFile) { strFileName = System.IO.Path.GetFileName(rasterUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(rasterUri.LocalPath); } await QueuedTask.Run(() => { RasterDataset rDataset = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. try { rDataset = geodatabase.OpenDataset <RasterDataset>(strFileName); } catch (GeodatabaseTableException e) { Debug.WriteLine("DisplayRasterAsync: Unable to open raster " + strFileName); Debug.WriteLine("DisplayRasterAsync: " + e.Message); return; } } // Create a new colorizer definition using default constructor. StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition(); RasterLayer rasterLayer = (RasterLayer)LayerFactory.Instance.CreateLayer(rasterUri, MapView.Active.Map); if (rasterLayer != null) { rasterLayer.SetTransparency(transparency); rasterLayer.SetName(displayName); } }); }
public static async Task <IList <BA_Objects.Interval> > ReadReclassRasterAttribute(Uri gdbUri, string rasterName) { IList <BA_Objects.Interval> lstInterval = new List <BA_Objects.Interval>(); await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (RasterDataset rasterDataset = geodatabase.OpenDataset <RasterDataset>(rasterName)) { RasterBandDefinition bandDefinition = rasterDataset.GetBand(0).GetDefinition(); Tuple <double, double> tupleSize = bandDefinition.GetMeanCellSize(); if (Math.Round(tupleSize.Item1, 5) != Math.Round(tupleSize.Item2, 5)) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The X and Y cell size values are not the same for " + gdbUri.LocalPath + "\\" + rasterName + ". This may cause problems with some BAGIS functions!!", "BAGIS-PRO"); } double cellSize = (tupleSize.Item1 + tupleSize.Item2) / 2; Raster raster = rasterDataset.CreateDefaultRaster(); using (Table rasterTable = raster.GetAttributeTable()) { TableDefinition definition = rasterTable.GetDefinition(); int idxName = definition.FindField(Constants.FIELD_NAME); int idxLowerBound = definition.FindField(Constants.FIELD_LBOUND); int idxUpperBound = definition.FindField(Constants.FIELD_UBOUND); int idxCount = definition.FindField(Constants.FIELD_COUNT); using (RowCursor cursor = rasterTable.Search()) { while (cursor.MoveNext()) { BA_Objects.Interval interval = new BA_Objects.Interval(); Row row = cursor.Current; interval.Value = row[Constants.FIELD_VALUE]; if (idxName > 0) { interval.Name = Convert.ToString(row[idxName]); } else { interval.Name = Constants.VALUE_UNKNOWN; } if (idxUpperBound > 0) { interval.UpperBound = Convert.ToDouble(row[idxUpperBound]); } if (idxLowerBound > 0) { interval.LowerBound = Convert.ToDouble(row[idxLowerBound]); } if (idxCount > 0) { interval.Area = cellSize *Convert.ToInt32(row[idxCount]); } lstInterval.Add(interval); } } } } }); return(lstInterval); }
public static async Task <TableStatisticsResult> GetRasterStats(Uri rasterUri, string field) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (rasterUri.IsFile) { strFileName = System.IO.Path.GetFileName(rasterUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(rasterUri.LocalPath); } RasterDataset rDataset = null; await QueuedTask.Run(() => { // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. try { rDataset = geodatabase.OpenDataset <RasterDataset>(strFileName); } catch (GeodatabaseTableException e) { Module1.Current.ModuleLogManager.LogError(nameof(GetRasterStats), "Unable to open raster " + strFileName); Module1.Current.ModuleLogManager.LogError(nameof(GetRasterStats), "Exception: " + e.Message); return; } } }); TableStatisticsResult tableStatisticsResult = null; if (rDataset != null) { await QueuedTask.Run(() => { Raster raster = rDataset.CreateRaster(new int[] { 0 }); if (raster != null) { var table = raster.GetAttributeTable(); if (table != null) { Field statField = table.GetDefinition().GetFields().First(x => x.Name.Equals(field)); StatisticsDescription statisticsDescription = new StatisticsDescription(statField, new List <StatisticsFunction>() { StatisticsFunction.Min, StatisticsFunction.Max }); TableStatisticsDescription tableStatisticsDescription = new TableStatisticsDescription(new List <StatisticsDescription>() { statisticsDescription }); IReadOnlyList <TableStatisticsResult> statResult = table.CalculateStatistics(tableStatisticsDescription); tableStatisticsResult = statResult[0]; } } }); } return(tableStatisticsResult); }
/// <summary> /// Function to identify rendered and source dataset pixel values for one or more /// raster, mosaic and image service layers. /// </summary> /// <param name="mapPoint">Map point to identify pixel values.</param> public static async void CustomRasterIdentify(MapPoint mapPoint) { // Create a new list of popup pages. var popupContents = new List <PopupContent>(); // Create an empty string that will represent what goes into a popup page. string identifiedVal = ""; // Create the popup pages to show. await QueuedTask.Run(() => { // Check if there is an active map view. if (MapView.Active != null) { // Get the active map view. var mapView = MapView.Active; // Get the list of selected layers. IReadOnlyList <Layer> selectedLayerList = MapView.Active.GetSelectedLayers(); if (selectedLayerList.Count == 0) { // If no layers are selected fill the popup page with the appropriate message. // Note: you can use html tags to format the text. identifiedVal += "<p>No Layers selected. Please select one or more Raster, Mosaic or Image Service layers.</p>"; // Add the popup page to the list of pages. popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify")); } else { // Iterate over the list of selected layers. foreach (Layer currentSelectedLayer in selectedLayerList) { #region Get a basic raster layer from the selected layer. BasicRasterLayer currentRasterLayer = null; if (currentSelectedLayer is MosaicLayer) { // If the current selected layer is a mosaic layer, MosaicLayer mosaicLayer = currentSelectedLayer as MosaicLayer; // Get the image sub-layer from the mosaic layer. This is a basic raster layer. currentRasterLayer = mosaicLayer.GetImageLayer() as BasicRasterLayer; } else if (currentSelectedLayer is BasicRasterLayer) { // If the current selected layer is a raster layer or image service layer, // both are already basic raster layers. currentRasterLayer = currentSelectedLayer as BasicRasterLayer; } else { // If the current selected layer is neither a mosaic nor a raster or image service layer, // fill the popup page with the appropriate message. identifiedVal += "<p>Selected layer is not a raster layer. Please select one or more Raster, Mosaic or Image Service layers.</p>"; // Add the popup page to the list of pages. popupContents.Add(new PopupContent(identifiedVal, "Custom Raster Identify for: " + currentSelectedLayer.Name)); continue; } #endregion #region Get the pixel value for the rendered raster. // Add the label for the rendered pixel value. identifiedVal += "<b>Rendered Pixel value: </b>"; // Get the raster from the current selected raster layer. Raster raster = currentRasterLayer.GetRaster(); // If the map spatial reference is different from the spatial reference of the raster, // set the map spatial reference on the raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name) { raster.SetSpatialReference(mapView.Map.SpatialReference); } // Convert the map point to be identified into an image point. Tuple <int, int> imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y); if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() || (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight()) { // If the point is outside the image, fill the pixel value with the appropriate message. identifiedVal += "Point is not within image. \n"; } else { // If the point is within the image. Iterate over the bands in the raster. for (int band = 0; band < raster.GetBandCount(); band++) { // Get the pixel value based on the band, column and row and add the // formatted pixel value to the popup page. if (band == 0) { identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } else { identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } } identifiedVal += "."; } // Add the rendered pixel value to the popup page contents. string htmlContent = "<p>" + identifiedVal + "</p>"; #endregion #region Get the pixel value for the source raster dataset. // Add the label for the source dataset pixel value. identifiedVal = "<b>Dataset Pixel value: </b>"; // Get the basic raster dataset from the raster. BasicRasterDataset basicRasterDataset = raster.GetRasterDataset(); if (!(basicRasterDataset is RasterDataset)) { // If the dataset is not a raster dataset, fill the pixel value with the appropriate message. identifiedVal += "Selected layer is not a Raster Layer. Please select one or more Raster, Mosaic or Image Service layers."; htmlContent += "<p>" + identifiedVal + "</p>"; popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name)); } // Get the raster dataset. RasterDataset rasterDataset = basicRasterDataset as RasterDataset; // Create a full raster from the raster dataset. raster = rasterDataset.CreateFullRaster(); // If the map spatial reference is different from the spatial reference of the raster, // Set the map spatial reference on the raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != raster.GetSpatialReference().Name) { raster.SetSpatialReference(mapView.Map.SpatialReference); } // Convert the map point to be identified to an image point. imagePoint = raster.MapToPixel(mapPoint.X, mapPoint.Y); if ((int)imagePoint.Item1 < 0 || (int)imagePoint.Item1 > raster.GetWidth() || (int)imagePoint.Item2 < 0 || (int)imagePoint.Item2 > raster.GetHeight()) { // If the point is outside the image, fill the pixel value with the appropriate message. identifiedVal += "Point is not within image. \n"; } else { // If the point is within the image. Iterate over the bands in the raster. for (int band = 0; band < raster.GetBandCount(); band++) { // Get the pixel value based on the band, column and row and add the // formatted pixel value to the popup page. if (band == 0) { identifiedVal += raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } else { identifiedVal += ", " + raster.GetPixelValue(band, (int)imagePoint.Item1, (int)imagePoint.Item2).ToString(); } } identifiedVal += "."; } // Add the source dataset pixel value to the popup page contents. htmlContent += "<p>" + identifiedVal + "</p>"; #endregion // Add the popup page to the list of pages. popupContents.Add(new PopupContent(htmlContent, "Custom Raster Identify for " + currentSelectedLayer.Name)); // Reset identifiedVal = ""; } } } }); // Show custom popup with the list of popup pages created above. MapView.Active.ShowCustomPopup(popupContents); }
/// <summary> /// Mask raster pixels based on the rectangle given and save the output in the /// current project folder. /// </summary> /// <param name="geometry">Rectangle to use to mask raster pixels.</param> public static async void MaskRaster(Geometry geometry) { try { // Check if there is an active map view. if (MapView.Active != null) { // Get the active map view. var mapView = MapView.Active; // Get the list of selected layers. IReadOnlyList <Layer> selectedLayerList = mapView.GetSelectedLayers(); if (selectedLayerList.Count == 0) { // If no layers are selected show a message box with the appropriate message. MessageBox.Show("No Layers selected. Please select one Raster layer."); } else { // Get the most recently selected layer. Layer firstSelectedLayer = mapView.GetSelectedLayers().First(); if (firstSelectedLayer is RasterLayer) { // Working with rasters requires the MCT. await QueuedTask.Run(() => { #region Get the raster dataset from the currently selected layer // Get the raster layer from the selected layer. RasterLayer currentRasterLayer = firstSelectedLayer as RasterLayer; // Get the raster from the current selected raster layer. Raster inputRaster = currentRasterLayer.GetRaster(); // Get the basic raster dataset from the raster. BasicRasterDataset basicRasterDataset = inputRaster.GetRasterDataset(); if (!(basicRasterDataset is RasterDataset)) { // If the dataset is not a raster dataset, show a message box with the appropriate message. MessageBox.Show("No Raster Layers selected. Please select one Raster layer."); return; } // Get the input raster dataset from the basic raster dataset. RasterDataset rasterDataset = basicRasterDataset as RasterDataset; #endregion #region Save a copy of the raster dataset in the project folder and open it // Create a full raster from the input raster dataset. inputRaster = rasterDataset.CreateFullRaster(); // Setup the paths and name of the output file and folder inside the project folder. string ouputFolderName = "MaskedOuput"; string outputFolder = Path.Combine(Project.Current.HomeFolderPath, ouputFolderName);; string outputName = "MaskedRaster.tif"; // Delete the output directory if it exists and create it. // Note: You will need write access to the project directory for this sample to work. if (Directory.Exists(outputFolder)) { Directory.Delete(outputFolder, true); } Directory.CreateDirectory(outputFolder); // Create a new file system connection path to open raster datasets using the output folder path. FileSystemConnectionPath outputConnectionPath = new FileSystemConnectionPath( new System.Uri(outputFolder), FileSystemDatastoreType.Raster); // Create a new file system data store for the connection path created above. FileSystemDatastore outputFileSytemDataStore = new FileSystemDatastore(outputConnectionPath); // Create a new raster storage definition. RasterStorageDef rasterStorageDef = new RasterStorageDef(); // Set the pyramid level to 0 meaning no pyramids will be calculated. This is required // because we are going to change the pixels after we save the raster dataset and if the // pyramids are calculated prior to that, the pyramids will be incorrect and will have to // be recalculated. rasterStorageDef.SetPyramidLevel(0); // Save a copy of the raster using the file system data store and the raster storage definition. inputRaster.SaveAs(outputName, outputFileSytemDataStore, "TIFF", rasterStorageDef); // Open the raster dataset you just saved. rasterDataset = OpenRasterDataset(outputFolder, outputName); // Create a full raster from it so we can modify pixels. Raster outputRaster = rasterDataset.CreateFullRaster(); #endregion #region Get the Min/Max Row/Column to mask // If the map spatial reference is different from the spatial reference of the input raster, // set the map spatial reference on the input raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != inputRaster.GetSpatialReference().Name) { inputRaster.SetSpatialReference(mapView.Map.SpatialReference); } // Use the MapToPixel method of the input raster to get the row and column values for the // points of the rectangle. Tuple <int, int> tlcTuple = inputRaster.MapToPixel(geometry.Extent.XMin, geometry.Extent.YMin); Tuple <int, int> lrcTuple = inputRaster.MapToPixel(geometry.Extent.XMax, geometry.Extent.YMax); int minCol = (int)tlcTuple.Item1; int minRow = (int)tlcTuple.Item2; int maxCol = (int)lrcTuple.Item1; int maxRow = (int)lrcTuple.Item2; // Ensure the min's are less than the max's. if (maxCol < minCol) { int temp = maxCol; maxCol = minCol; minCol = temp; } if (maxRow < minRow) { int temp = maxRow; maxRow = minRow; minRow = temp; } // Ensure the mins and maxs are within the raster. minCol = (minCol < 0) ? 0 : minCol; minRow = (minRow < 0) ? 0 : minRow; maxCol = (maxCol > outputRaster.GetWidth()) ? outputRaster.GetWidth() : maxCol; maxRow = (maxRow > outputRaster.GetHeight()) ? outputRaster.GetHeight() : maxRow; #endregion #region Mask pixels based on the rectangle drawn by the user // Calculate the width and height of the pixel block to create. int pbWidth = maxCol - minCol; int pbHeight = maxRow - minRow; // Check to see if the output raster can be edited. if (!outputRaster.CanEdit()) { // If not, show a message box with the appropriate message. MessageBox.Show("Cannot edit raster :("); return; } // Create a new pixel block from the output raster of the height and width calculated above. PixelBlock currentPixelBlock = outputRaster.CreatePixelBlock(pbWidth, pbHeight); // Iterate over the bands of the output raster. for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++) { // For each band, clear the pixel block. currentPixelBlock.Clear(plane); //Array noDataMask = currentPixelBlock.GetNoDataMask(plane, true); //for (int i = 0; i < noDataMask.GetLength(0); i++) // noDataMask.SetValue(Convert.ToByte(0), i); //currentPixelBlock.SetNoDataMask(plane, noDataMask); } // Write the cleared pixel block to the output raster dataset. outputRaster.Write(minCol, minRow, currentPixelBlock); // Refresh the properties of the output raster dataset. outputRaster.Refresh(); #endregion // Create a new layer from the masked raster dataset and add it to the map. LayerFactory.Instance.CreateLayer(new Uri(Path.Combine(outputFolder, outputName)), mapView.Map); // Disable the layer representing the original raster dataset. firstSelectedLayer.SetVisibility(false); }); } else { // If the selected layer is not a raster layer show a message box with the appropriate message. MessageBox.Show("No Raster layers selected. Please select one Raster layer."); } } } } catch (Exception exc) { MessageBox.Show("Exception caught in MaskRaster: " + exc.Message); } }
public async void RasterDatasetSnippets() { try { #region Open raster dataset in a folder. // Create a FileSystemConnectionPath using the folder path. FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(@"C:\Temp"), FileSystemDatastoreType.Raster); // Create a new FileSystemDatastore using the FileSystemConnectionPath. FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath); // Open the raster dataset. RasterDataset fileRasterDataset = dataStore.OpenDataset <RasterDataset>("Sample.tif"); #endregion #region Open raster dataset in a geodatabase. // Create a FileGeodatabaseConnectionPath using the path to the gdb. Note: This can be a path to a .sde file. FileGeodatabaseConnectionPath geodatabaseConnectionPath = new FileGeodatabaseConnectionPath(new Uri(@"C:\Temp\rasters.gdb")); // Create a new Geodatabase object using the FileGeodatabaseConnectionPath. Geodatabase geodatabase = new Geodatabase(geodatabaseConnectionPath); // Open the raster dataset. RasterDataset gdbRasterDataset = geodatabase.OpenDataset <RasterDataset>("sample"); #endregion RasterDataset rasterDataset = fileRasterDataset; #region Get the raster dataset definition from a raster dataset. await QueuedTask.Run(() => { RasterDatasetDefinition rasterDatasetDefinition = rasterDataset.GetDefinition(); rasterDatasetDefinition.GetBandCount(); }); #endregion { #region Access rows in a raster attribute table. var raster = MapView.Active.Map.GetLayersAsFlattenedList().OfType <RasterLayer>().FirstOrDefault(); if (raster != null) { await QueuedTask.Run(() => { var rasterTbl = raster.GetRaster().GetAttributeTable(); var cursor = rasterTbl.Search(); while (cursor.MoveNext()) { var row = cursor.Current; } }); } #endregion } { #region Create a raster cursor to iterate through the raster data. await QueuedTask.Run(() => { // Create a full raster from the raster dataset. ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster(); // Calculate size of pixel blocks to process. Use 1000 or height/width of the raster, whichever is smaller. int pixelBlockHeight = raster.GetHeight() > 1000 ? 1000 : raster.GetHeight(); int pixelBlockWidth = raster.GetWidth() > 1000 ? 1000 : raster.GetWidth(); // Create the raster cursor using the height and width calculated. RasterCursor rasterCursor = raster.CreateCursor(pixelBlockWidth, pixelBlockHeight); // Use a do-while loop to iterate through the pixel blocks of the raster using the raster cursor. do { // Get the current pixel block from the cursor. using (PixelBlock currentPixelBlock = rasterCursor.Current) { // Do something with the pixel block... } // Once you are done, move to the next pixel block. } while (rasterCursor.MoveNext()); }); #endregion } { #region Read and Write pixels from and to a raster dataset using pixel blocks. await QueuedTask.Run(() => { // Create a full raster from the raster dataset. ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster(); // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller. int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight(); int pixelBlockWidth = raster.GetWidth() > 128 ? 128 : raster.GetWidth(); // Create a new (blank) pixel block. PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight); // Read pixel values from the raster dataset into the pixel block starting from the given top left corner. raster.Read(0, 0, currentPixelBlock); // Do something with the pixel block... // Write the pixel block to the raster dataset starting from the given top left corner. raster.Write(0, 0, currentPixelBlock); }); #endregion } { // Create a full raster from the raster dataset. ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster(); // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller. int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight(); int pixelBlockWidth = raster.GetWidth() > 128 ? 128 : raster.GetWidth(); // Create a new (blank) pixel block. PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight); #region Process pixels using a pixel block await QueuedTask.Run(() => { // Read pixel values from the raster dataset into the pixel block starting from the given top left corner. raster.Read(0, 0, currentPixelBlock); // For each plane (band) in the pixel block for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++) { // Get a copy of the array of pixels from the pixel block corresponding to the current plane. Array sourcePixels = currentPixelBlock.GetPixelData(plane, true); // Get the height and width of the pixel block. int pBHeight = currentPixelBlock.GetHeight(); int pBWidth = currentPixelBlock.GetWidth(); // Iterate through the pixels in the array. for (int i = 0; i < pBHeight; i++) { for (int j = 0; j < pBWidth; j++) { // Get the NoData mask value to see if the pixel is a valid pixel. if (Convert.ToByte(currentPixelBlock.GetNoDataMaskValue(plane, j, i)) == 1) { // Get the pixel value from the array and process it (add 5 to the value). // Note: This is assuming the pixel type is Unisigned 8bit. int pixelValue = Convert.ToInt16(sourcePixels.GetValue(j, i)) + 5; // Make sure the pixel value does not go above the range of the pixel type. pixelValue = pixelValue > 254 ? 254 : pixelValue; // Set the new pixel value to the array. // Note: This is assuming the pixel type is Unisigned 8bit. sourcePixels.SetValue(Convert.ToByte(pixelValue), j, i); } } } // Set the modified array of pixels back to the pixel block. currentPixelBlock.SetPixelData(plane, sourcePixels); } // Write the pixel block to the raster dataset starting from the given top left corner. raster.Write(0, 0, currentPixelBlock); }); #endregion #region Calculate Raster statistics //If a raster dataset has statistics, you can create a raster layer and get these statistics by accessing the colorizer. await QueuedTask.Run(() => { //Accessing the raster layer var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <BasicRasterLayer>().FirstOrDefault(); //Getting the colorizer var colorizer = lyr.GetColorizer() as CIMRasterStretchColorizer; //Accessing the statistics var stats = colorizer.StretchStats; var max = stats.max; var min = stats.min; }); #endregion } } catch (Exception) { } }
public OpenTopographyElement(Helper.WGS84 coordinates, RasterDataset dataset = RasterDataset.SRTMGL1, OutputFormat outputFormat = OutputFormat.GTiff) { this.coordinates = coordinates; this.dataset = dataset; this.outputFormat = outputFormat; }