How to add rasters using a RasterMathSupportOp


This sample code demonstrate how to add two rasters using the IMathSupportOp::Plus method of RasterMathSupportOp object.

How to use

  1. Start ArcMap and add two rasters.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst or 3D Analyst extension is checked.
  4. Add reference to ESRI GeoAnalyst Object Library.
  5. Run the sub from the Macros dialog.
[VBA]
Sub RasterMathSupportOp_Plus()
    'Get the Map
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    
    'Get the first raster from the first layer in ArcMap
    Dim pLayer1 As ILayer
    Set pLayer1 = pMap.Layer(0)
    If Not TypeOf pLayer1 Is IRasterLayer Then
        Exit Sub
    End If
    Dim pRasLayer1 As IRasterLayer
    Set pRasLayer1 = pLayer1
    Dim pRas1 As IRaster
    Set pRas1 = pRasLayer1.Raster
    
    'Get the second raster from the second layer in ArcMap
    Dim pLayer2 As ILayer
    Set pLayer2 = pMap.Layer(1)
    If Not TypeOf pLayer2 Is IRasterLayer Then
        Exit Sub
    End If
    Dim pRasLayer2 As IRasterLayer
    Set pRasLayer2 = pLayer2
    Dim pRas2 As IRaster
    Set pRas2 = pRasLayer2.Raster
    
    'Create a Spatial operator
    Dim pMathOp As IMathSupportOp
    Set pMathOp = New RasterMathSupportOp
    
    'Set output workspace
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pMathOp
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Perform the operation
    Dim pOutRaster As IRaster
    Set pOutRaster = pMathOp.Plus(pRas1, pRas2)
    
    'Create a raster layer and add it into ArcMap
    Dim pOutRasLayer As IRasterLayer
    Set pOutRasLayer = New RasterLayer
    pOutRasLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pOutRasLayer
End Sub