BMP width and height, BinaryReader Learn programming with Visual Basic (VB.net) exercises

Lesson:

File Management


Exercise:

BMP width and height, BinaryReader 61


Objetive:

reate a Visual Basic (VB.net) program to display the width and the height of a BMP file, using a BinaryReader.

The structure of the header of a BMP file is:

File type (letters BM)
0-1

FileSize
2-5

Reserved
6-7

Reserved
8-9

Start of image data
10-13

Sizeofbitmapheader
14-17

Width (pixels)
18-21

Height (pixels)
22-25

Numberofplanes
26-27

Sizeofeachpoint
28-29

Compression(0=notcompressed)
30-33

Imagesize
34-37

Horizontal resolution
38-41

Verticalresolution
42-45

Sizeofcolortable
46-49


Code:

Imports System
Imports System.IO
Public Class BmpHeightWidth
    Public Shared Sub Main()
        Dim myFile As BinaryReader
        Dim b1, b2 As Byte
        Dim width, height As Integer
        myFile = New BinaryReader(File.Open("example.bmp", FileMode.Open))
        b1 = myFile.ReadByte()
        b2 = myFile.ReadByte()

        If (b1 = &H42) AndAlso (b2 = &H4D) Then
            Console.WriteLine("It seems to be a BMP file")
            myFile.BaseStream.Seek(18, SeekOrigin.Begin)
            width = myFile.ReadInt32()
            height = myFile.ReadInt32()
            Console.WriteLine("Width: {0} pixels", width)
            Console.WriteLine("Height: {0} pixels", height)
        Else
            Console.WriteLine("It DOES NOT seem to be a BMP file")
        End If

        myFile.Close()
    End Sub
End Class