Hi guys,
I would appreciate it if you could help me reading a 16bit binary file (tiff image). Since the file is in 16bit, pixels of the file stores values ranging from 1200 to 4500. I want to retrieve those values. I used ReadUInt16 since the file has a 2byte data type but keep getting EnfofStreamException Unhandled error.

Dim f1 As New System.IO.FileInfo(TextBox2.Text)
            fLen1 = f1.Length
            Dim snglRead As Single
            Dim i As Integer
            For i = 0 To fLen1 - 1
                snglRead = br.ReadUInt16 'Exception thrown here
                snglOutput = snglRead
                bw.Write(snglOutput)
            Next

Binary reads use byte arrays for the container. If you need to store the data as 16 bit values then you have to combine the bytes manually as in

Dim bin8() As Byte = System.IO.File.ReadAllBytes("d:\test.txt")
Dim bin16((UBound(bin8)) \ 2) As UInt16

Try
    For i As UInteger = 0 To UBound(bin16)
        bin16(i) = bin8(2 * i) + 256 * bin8(2 * i + 1)
    Next
Catch ex As IndexOutOfRangeException
    bin16(UBound(bin16)) = bin8(UBound(bin8))
End Try

The line that combines the two values swaps the order of the bytes. Depending on whether you want "big-endian" or "little-endian" you may want to switch the calculation to

bin16(i) = bin8(2 * i + 1) + 256 * bin8(2 * i)

The above code uses a Try/Catch in case the file contains an odd number of bytes in which case the last byte has no other byte to "partner" with, thus requiring a special case. You could always bundle this up into a custom "ReadBin16" Function that returns the bin16 array as its value.

If this thread has been solved then please mark it as such.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.