Programming Course in C# ¡Free!

BMP width & height, BinaryReader

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a C# 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:
TYPE OF INFORMATION
POSITIONINTHEFILE
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
Importantcolorscounter
50-53

Output



Solution


using System;
using System.IO;

public class BmpMesures
{
public static void Main() 
{    
byte b1, b2;
int width, height;

BinaryReader file = 
new BinaryReader( File.Open("test.bmp", FileMode.Open));

b1 = file.ReadByte();
b2 = file.ReadByte();

if (b1 == 0x42 && b2 == 0x4D)  
{
file.BaseStream.Seek(18, SeekOrigin.Begin);

width = file.ReadInt32();
height = file.ReadInt32();

Console.WriteLine("Width is of {0} pixels", width);
Console.WriteLine("Height is of {0} pixels", height);
}
else
Console.WriteLine("It not .BMP");

file.Close();
}
}