How to create an in-memory raster dataset


This sample shows how to create an in-memory raster dataset.

How to use

  1. Reference libraries: ESRI.ArcGIS.DataSourcesRaster, ESRI.ArcGIS.Geodatabase, ESRI.ArcGIS.Geometry.
  2. Call this function from your code.
[VBA]
Sub CreateInMemoryRaster()
    On Error GoTo ERH
    'Create a raster workspace
    Dim pWs As IRasterWorkspace2
    Set pWs = OpenRasterWorkspace("c:\temp")
    
    'Define origin of the raster dataset
    Dim pOrigin As IPoint
    Set pOrigin = New Point
    pOrigin.PutCoords 10, 10
    
    'Define the size of the raster, usually small to be hold in memory.
    Dim Width As Long, Height As Long
    Width = 256
    Height = 256
    
    'Create the in memory raster dataset using string "MEM" for the format and empty string for the file name.
    Dim pDs As IRasterDataset
    Set pDs = pWs.CreateRasterDataset("", "MEM", pOrigin, Width, Height, 30, 30, 1, PT_UCHAR, Nothing, True)
    
    'Create Raster and write pixel values.
    Dim pRaster As IRaster
    Dim pEdit As IRasterEdit
    Dim pPB As IPixelBlock3
    Dim pPnt As IPnt
    Dim v As Variant, i As Long, j As Long
    Set pPnt = New Pnt
    
    Set pRaster = pDs.CreateDefaultRaster
    pPnt.SetCoords Width, Height
    Set pPB = pRaster.CreatePixelBlock(pPnt)
    v = pPB.PixelData(0)
    For i = 0 To Height - 1
        For j = 0 To Width - 1
            v(i, j) = (i + j) / 2
        Next j
    Next i
    pPB.PixelData(0) = v
    Set pEdit = pRaster
    pPnt.SetCoords 0, 0
    pEdit.Write pPnt, pPB
    
    
    'Send the Raster to display or to other operation.
    Dim pMxdoc As IMxDocument
    Set pMxdoc = ThisDocument
    Dim pLy As IRasterLayer
    Set pLy = New RasterLayer
    pLy.CreateFromRaster pRaster
    
    pMxdoc.FocusMap.AddLayer pLy
    pMxdoc.ActiveView.Refresh
    
    'Release objects.
    Set v = Nothing
    Set pPB = Nothing
    Set pEdit = Nothing
    Set pRaster = Nothing
    Set pDs = Nothing
    Set pWs = Nothing
    Exit Sub
ERH:
    MsgBox Err.Description
End Sub


Public Function OpenRasterWorkspace(sPath As String) As IRasterWorkspace2
    
    ' Create RasterWorkspace
    Dim pWsFact As IWorkspaceFactory
    Set pWsFact = New RasterWorkspaceFactory
    If pWsFact.IsWorkspace(sPath) Then
        Set createRasterWorkspace = pWsFact.OpenFromFile(sPath, 0)
    End If
    Set pWsFact = Nothing
    
End Function