How to reclassify a raster using a string field


This sample code demonstrates i) how to reclassify a raster using a string field, ii) how to use RasterReclassOp, StringRemap and RasterDescriptor objects

How to use

  1. Start ArcMap and add a raster dataset that has a string field.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst extension is checked.
  4. Add reference to ESRI SpatialAnalyst Object Library.
  5. Add reference to ESRI GeoAnalyst Object Library.
  6. Change field name (sFieldName) and remap string (pStringRemap)in the code.
  7. Run the sub from the Macros dialog.
[VBA]
Sub ReclassifyByStringField()
    'Get the focused map from MapDocument
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Set pMxDoc = ThisDocument
    Set pMap = pMxDoc.FocusMap
    
    'Get the input raster from the first layer in ArcMap
    Dim pLayer As ILayer
    Set pLayer = pMap.Layer(0)
    If Not TypeOf pLayer Is IRasterLayer Then
        Exit Sub
    End If
    
    Dim pRasLayer As IRasterLayer
    Set pRasLayer = pLayer
    Dim pInRaster As IRaster
    Set pInRaster = pRasLayer.Raster
    
    'Create a raster descriptor and specify the field to be used for reclassify
    Dim sFieldName As String
    sFieldName = "Landuse"
    
    Dim pRasDescriptor As IRasterDescriptor
    Set pRasDescriptor = New RasterDescriptor
    pRasDescriptor.Create pInRaster, Nothing, sFieldName
    
    'Create a RasterReclassOp operator
    Dim pReclassOp As IReclassOp
    Set pReclassOp = New RasterReclassOp
    
    'Set output workspace
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pReclassOp
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Create a StringRemap object and specify remap
    Dim pStringRemap As IStringRemap
    Set pStringRemap = New StringRemap
    
    pStringRemap.MapString "Water", 1
    pStringRemap.MapString "Forest", 2
    pStringRemap.MapString "Agriculture", 3
    pStringRemap.MapStringToNoData "Wetlands"
    
    'Reclassify the input raster
    Dim pOutRaster As IRaster
    Set pOutRaster = pReclassOp.ReclassByRemap(pRasDescriptor, pStringRemap, False)
    
    'Add output into ArcMap as a raster layer
    Dim pOutRasLayer As IRasterLayer
    Set pOutRasLayer = New RasterLayer
    pOutRasLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pOutRasLayer
End Sub