How to create tiles from a raster dataset


This sample shows how to tile up a raster dataset to specified size and save each tile to a raster dataset.

How to use

  1. Add these functions to your project.
  2. Call the top-level function (first one listed) from your code.
[VBA]
Public Sub subset(pRasterDs As IRasterDataset, _
                  pOutputWs As IWorkspace, _
                  row As Long, Column As Long)
    
    
    ' This procedure tiles up a raster dataset into many subsets of
    ' the specified size (row * column)
    
    Dim pRaster As IRasterProps
    Dim pSaveAs As ISaveAs
    Dim iWidth As Long, iHeight As Long
    Dim iCntX As Long, iCntY As Long
    Dim pExt As IEnvelope, pOrg As IEnvelope
    Dim pDs As IDataset
    Dim i As Long, j As Long, rowleft As Long, colleft As Long
    
    On Error GoTo er
    
    ' ++ if rasterdef is missing, create one with specified/unknown spatialreference
    If pRasterDef Is Nothing Then
        Set pRasterDef = createRasterDef(False, pSR)
    End If
    
    ' Get raster object to manipulate
    Set pRaster = pRasterDs.CreateDefaultRaster
    
    ' QI dataset to get name
    Set pDs = pRasterDs
    
    ' Calculate how many subsets will be created
    iWidth = pRaster.Width
    iHeight = pRaster.Height
    iCntX = iWidth \ Column
    iCntY = iHeight \ row
    rowleft = iHeight Mod row
    colleft = iWidth Mod Column
    
    ' Loop through all the subsets and create IMGs
    For i = 0 To iCntX
        iWidth = Column
        iHeight = row
        
        If i = iCntX Then
            iWidth = colleft
        End If
        
        If iWidth > 0 Then
            For j = 0 To iCntY
                Set pRaster = pRasterDs.CreateDefaultRaster
                Set pOrg = pRaster.Extent
                Set pExt = New Envelope
                
                If j = iCntY Then
                    iHeight = rowleft
                End If
                
                If iHeight > 0 Then ' Set the extents of the output raster
                    pExt.XMin = pOrg.XMin + i * Column * pRaster.MeanCellSize.X
                    pExt.YMin = pOrg.YMin + j * row * pRaster.MeanCellSize.Y
                    pExt.XMax = pOrg.XMin + (i * Column + iWidth) * pRaster.MeanCellSize.X
                    pExt.YMax = pOrg.YMin + (j * row + iHeight) * pRaster.MeanCellSize.Y
                    pRaster.Extent = pExt
                    pRaster.Width = iWidth
                    pRaster.Height = iHeight
                    ' Save to a file with datasetname_Xtilenumber_Ytilenumber.img
                    Set pSaveAs = pRaster
                    pSaveAs.SaveAs Replace(pDs.Name, ".", "_") + "_" + CStr(i) + "_" + CStr(j) + ".img", pOutputWs, "IMAGINE Image"
                End If
            Next j
        End If
    Next i
    
    Set pSaveAs = Nothing
    Set pRasterDs = Nothing
    Set pDs = Nothing
    Set pExt = Nothing
    Set pOrg = Nothing
    
    Exit Sub
    
er:
    MsgBox Err.Description
End Sub