Using PixelBlock and RawPixel

Created:4/4/2001
Description:

This sample demonstrates how to write pixel values to a raster dataset using PixelBlock and RawPixel.

How to use:
  1. Call this procedure from VB or VBA.
Sub UsingPixelBlockAndRawPixel(sPath As String, sFileName As String)
     ' sFileName: name of output raster dataset
    ' sPath: path of the output raster dataset
    
    ' Create RasterWorkspace
     Dim pRWS As IRasterWorkspace2
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    If Not pWSF.IsWorkspace(sPath) Then Exit Sub
    Set pRWS = pWSF.OpenFromFile(sPath, 0)

     ' To create a raster dataset, define the origin
     Dim pOrigin As IPoint
    Set pOrigin = New Point
    pOrigin.X = 1200
    pOrigin.Y = 1500
    
     ' Create a raster dataset with Imagine format
     Dim pRasterDS As IRasterDataset
    Set pRasterDS = pRWS.CreateRasterDataset(sFileName, "IMAGINE Image", pOrigin, 100, 100, 30, 30, 1, PT_LONG, Nothing, True)    

     ' Create a default raster and QI raster properties interface
     Dim pRaster As IRaster
    Set pRaster = pRasterDS.CreateDefaultRaster
    Dim pRasProps As IRasterProps
    Set pRasProps = pRaster

     ' Get RasterBand from the raster
     Dim pBand As IRasterBand
    Dim pBandCol As IRasterBandCollection
    Set pBandCol = pRaster
    Set pBand = pBandCol.Item(0)

     ' QI RawPixel interface
     Dim pRawPixel As IRawPixels
    Set pRawPixel = pBand    

     ' Create a DblPnt to hold the PixelBlock size
     Dim pSize As IPnt
    Set pSize = New DblPnt
    pSize.SetCoords pRasProps.Width, pRasProps.Height

     ' Create PixelBlock with defined size
     Dim pBlock As IPixelBlock
    Set pBlock = pRawPixel.CreatePixelBlock(pSize)

     ' Get the SafeArray associated with the first band 
   (It does not work with raster that is 16 bit unsigned integer since VB does not support this data type). 
     Dim pSafeArray As Variant
    pSafeArray = pBlock.SafeArray(0)
     ' Loop through the SafeArray and set value to each pixel
     Dim I, J As Integer
    For I = 0 To pSize.X - 1
        For J = 0 To pSize.Y - 1
            pSafeArray(I, J) = I + J
        Next J
    Next I

     ' Create a DblPnt to hold the top left corner
     Dim pPnt As IPnt
    Set pPnt = New DblPnt
    pPnt.SetCoords 0, 0

     ' Write the PixelBlock to raster band
     pRawPixel.Write pPnt, pBlock

     ' Release memeory
     Set pRawPixel = Nothing
    Set pPnt = Nothing
    Set pSize = Nothing
    Set pBlock = Nothing
    Set pBand = Nothing
    Set pBandCol = Nothing
    Set pRasterDS = Nothing
    Set pRaster = Nothing
    Set pRasProps = Nothing
    Set pOrigin = Nothing
    Set pRWS = Nothing
    Set pWSF = Nothing
End Sub