Thursday, 1 September 2016

arcobjects - How can I add a new field in a raster attribute table and loop through it?


I am working with an existing raster attribute table. I wonder how can I add a new field to it and then loop through the existing records to populate this new field? Of course I have done this many times for a feature class and a database table but I do not know how to do it with a raster table. I work with VBA. Any code please? Thanks.



Answer




VBA sample code is here:



Public Sub CalculateArea(raster As IRaster, areaField As String)
Dim bandCol As IRasterBandCollection
Dim band As IRasterBand

Set bandCol = raster
Set band = bandCol.Item(0)

Dim hasTable As Boolean

band.hasTable hasTable
If (hasTable = False) Then
Exit Sub
End If

If (AddVatField(raster, areaField, esriFieldTypeDouble, 38) = True) Then
' calculate cell size
Dim rstProps As IRasterProps
Set rstProps = raster


Dim pnt As IPnt
Set pnt = rstProps.MeanCellSize

Dim cellSize As Double
cellSize = (pnt.X + pnt.Y) / 2#

' get fields index
Dim attTable As ITable
Set attTable = band.AttributeTable


Dim idxArea As Long, idxCount As Long
idxArea = attTable.FindField(areaField)
idxCount = attTable.FindField("COUNT")

' using update cursor
Dim gridTableOp As IGridTableOp
Set gridTableOp = New gridTableOp

Dim cellCount As Long, cellArea As Double


Dim updateCursor As ICursor, updateRow As IRow
Set updateCursor = gridTableOp.Update(band.RasterDataset, Nothing, False)
Set updateRow = updateCursor.NextRow()
Do Until updateRow Is Nothing
cellCount = CLng(updateRow.Value(idxCount))
cellArea = cellCount * (cellSize * cellSize)

updateRow.Value(idxArea) = cellArea
updateCursor.updateRow updateRow


Set updateRow = updateCursor.NextRow()
Loop

End If
End Sub


Private Function AddVatField(raster As IRaster, fieldName As String, fieldType As esriFieldType, fieldLength As Long) As Boolean
Dim bandCol As IRasterBandCollection
Dim band As IRasterBand


Set bandCol = raster
Set band = bandCol.Item(0)

Dim hasTable As Boolean
band.hasTable hasTable

If (hasTable = True) Then
Dim attTable As ITable
Set attTable = band.AttributeTable


If (attTable.FindField(fieldName) -1) Then
AddVatField = True
Exit Function
End If

Dim newField As IField
Dim fieldEdit As IFieldEdit

Set newField = New Field

Set fieldEdit = newField

With fieldEdit
.Name = fieldName
.Type = fieldType
.Editable = True
.IsNullable = True
.Length = fieldLength
End With


Dim gridTableOp As IGridTableOp
Set gridTableOp = New gridTableOp
gridTableOp.AddField band.RasterDataset, newField

AddVatField = True
Exit Function
End If

AddVatField = False
End Function

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...