Search code examples
vb.netbinaryreader

Read two .TIF files from an .IMG file


Dealing with some legacy code that parses .TIF images (front and back images for checks) from an .IMG file. For example, I have the following file: 05090001.IMG and then I have the following values about that file:

FrontStart: 8 | FrontLength: 10600 | RearStart: 10608 | RearLength: 6372

The size of 05090001.IMG is 16980 bytes, so it seems that the front image should be 10600 bytes and does in fact create a valid .TIF file while the rear image always ends up corrupt.

This is the existing code that retrieves the front .TIF file:

Dim fs As New FileStream(Me.FileName, FileMode.Open, FileAccess.Read)
Dim sr As New BinaryReader(fs)
Dim fname As String = {long formula to generate fname}

Dim fsFront As New FileStream(fname & "_Front.tif", FileMode.Create)
Dim swFront As New BinaryWriter(fsFront)
Dim imgBytesFront As Byte()

fs = New FileStream(Path.Combine(DownImageFiles, dr("ImgFile")), FileMode.Open, FileAccess.Read)
sr = New BinaryReader(fs)
imgBytesFront = sr.ReadBytes(dr("FrontLength"))

swFront.Write(imgBytesFront)
swFront.Close()
fsFront.Close()

I'm trying to add similar code to access the rear image file:

Dim fsRear As New FileStream(fname & "_Rear.tif", FileMode.Create)
Dim swRear As New BinaryWriter(fsRear)
Dim imgBytesRear As Byte()

fs = New FileStream(Path.Combine(DownImageFiles, dr("ImgFile")), FileMode.Open, FileAccess.Read)
Using br As New BinaryReader(fs)
    br.BaseStream.Seek(Long.Parse(dr("FrontLength"), Globalization.NumberStyles.Integer), SeekOrigin.Begin)
    imgBytesRear = br.ReadBytes(dr("RearLength"))
End Using

imgBytesRear = sr.ReadBytes(dr("RearLength"))
swRear.Write(imgBytesRear)
swRear.Close()
fsRear.Close()

This generates an image, but Windows says it is "damaged, corrupted, or is too large".

Any ideas what I'm missing? Am I using the Seek method properly? Am I somehow reading the first 6372 bytes again instead of skipping the first 10600 and starting there? Any help greatly appreciated!


Solution

  • Thanks to several people in the comments above, I found that simply loading the .IMG file in as a System.Drawing.Image, I could then split it into individual page files.

    Dim tiffCheck As Image = Image.FromFile(Path.Combine(DownImageFiles, dr("ImgFile")))
    

    After that, I essentially followed the solution under the Split() function here: https://code.msdn.microsoft.com/windowsdesktop/Split-multi-page-tiff-file-058050cc