' Collection of code snippets by Arne Vajhøj 
' (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
Imports System
Imports System.IO

Namespace E
    Public Class TiffDim
        Public Structure HWDim
            Public H As Integer
            Public W As Integer
            Public XRes As Double
            Public YRes As Double
        End Structure
        Private Shared Function ReadWord(stm As Stream, ix As Integer) As Short
            stm.Seek(ix, SeekOrigin.Begin)
            Dim word As Byte() = New Byte(1) {}
            stm.Read(word, 0, 2)
            Return BitConverter.ToInt16(word, 0)
        End Function
        Private Shared Function ReadDWord(stm As Stream, ix As Integer) As Integer
            stm.Seek(ix, SeekOrigin.Begin)
            Dim dword As Byte() = New Byte(3) {}
            stm.Read(dword, 0, 4)
            Return BitConverter.ToInt32(dword, 0)
        End Function
        Private Shared Function ReadRational(stm As Stream, ix As Integer) As Double
            Return ReadDWord(stm, ix) * 1 / ReadDWord(stm, ix + 4)
        End Function
        Public Shared Function Find(fnm As String) As HWDim
            Dim res As New HWDim()
            Using stm As Stream = New FileStream(fnm, FileMode.Open, FileAccess.Read)
                Dim ix As Integer = ReadWord(stm, 4)
                While True
                    Dim ntag As Integer = ReadWord(stm, ix)
                    ix += 2
                    For i As Integer = 0 To ntag - 1
                        Dim tagid As Integer = ReadWord(stm, ix)
                        If tagid = 257 Then
                            res.H = ReadDWord(stm, ix + 8)
                        ElseIf tagid = 256 Then
                            res.W = ReadDWord(stm, ix + 8)
                        ElseIf tagid = 282 Then
                            res.XRes = ReadRational(stm, ReadDWord(stm, ix + 8))
                        ElseIf tagid = 283 Then
                            res.YRes = ReadRational(stm, ReadDWord(stm, ix + 8))
                        End If
                        ix += 12
                    Next
                    ix = ReadDWord(stm, ix)
                    If ix = 0 Then
                       Exit While
                    End If
                End While
            End Using
            Return res
        End Function
        Public Shared Sub Main(args As String())
            Dim hw As HWDim = TiffDim.Find("C:\test.tif")
            Console.WriteLine(hw.H & " " & hw.W & " " & hw.XRes & " " & hw.YRes)
        End Sub
    End Class
End Namespace
