HOW TO
Instructions provided explain how to write the pixel value for each pixel of each band of a multi-band raster layer to a text file using Visual Basic for Applications (VBA) code. The text file will be located in C:\Temp folder.
Warning:
This process may take a long time to complete depending on the number of bands and resolution of the raster image.
Note:
For more information on creating a UIControl, see the ArcGIS Desktop Help topic 'Creating custom commands with VBA and UI Controls.'
Code:
'Notes:
'The following code sample will write the pixel values to a text file
'for the top layer, first band of the raster.
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pLayer As ILayer
Set pLayer = pMxDoc.FocusMap.Layer(0)
' Check if layer is a raster layer
If TypeOf pLayer Is IRasterLayer Then
Dim pRasterLayer As IRasterLayer
Set pRasterLayer = pLayer
Dim pRaster As IRaster
Set pRaster = pRasterLayer.Raster
Dim pRasterBandCol As IRasterBandCollection
Set pRasterBandCol = pRaster
Dim pRawpixel As IRawPixels
Dim pRasterProps As IRasterProps
Dim pPnt As IPnt
Dim pSize As IPnt
Dim pPixelBlock As IPixelBlock3
Dim pPixelData
Dim lPixelValue As Long
Dim sTxtFile As String
Dim objFSO
Dim objTextStream
sTxtFile = "C:\temp\" & pRasterLayer.Name & ".txt"
'Create text file with layer name as filename
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateTextFile sTxtFile, True
'Open text file
Set objTextStream = objFSO.OpenTextFile(sTxtFile, 2, True)
Dim h As Integer, i As Long, j As Long
For h = 0 To pRasterBandCol.Count - 1
Set pRawpixel = pRasterBandCol.Item(h)
Set pRasterProps = pRawpixel
Set pPnt = New DblPnt
pPnt.SetCoords 0, 0
Set pSize = New DblPnt
pSize.SetCoords pRasterProps.Width, pRasterProps.Height
Set pPixelBlock = pRawpixel.CreatePixelBlock(pSize)
' Read pixelblock
pRawpixel.Read pPnt, pPixelBlock
' Get pixeldata array
pPixelData = pPixelBlock.PixelDataByRef(0)
' Write band heading information for each band
objTextStream.WriteLine "All the pixel values for band index " & h & " from " & pRasterLayer.Name
objTextStream.WriteLine "(X, Y) = Value"
objTextStream.WriteLine ""
'Go through each pixel and write its value to text file.
'Starting with top left corner location (0, 0)
For i = 0 To pRasterProps.Width - 1
For j = 0 To pRasterProps.Height - 1
pRawpixel.Read pPnt, pPixelBlock
lPixelValue = pPixelBlock.GetVal(0, i, j)
objTextStream.WriteLine "(" & i & ", " & j & ") = " & lPixelValue
Next j
Next i
objTextStream.WriteLine ""
objTextStream.WriteLine "-------------------------------------------------------"
Next h
'Close the file and clean up
objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
Else
MsgBox "Top layer is not a raster layer." & vbNewLine & _
"Text file was not created.", vbExclamation, "Error"
Exit Sub
End If
Article ID:000008769
Get help from ArcGIS experts
Download the Esri Support App