Programming Course in C# ¡Free!

BMP width & height, FileStream

 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 FileStream.

Remember the structure of the header:

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


public class BmpFileStream 
{
public static void Main()
{
const int SIZE = 54;
byte[] data;
int width, height;

Console.Write("Enter the name: ");
string name = Console.ReadLine();

try
{
if(File.Exists(name))
{
FileStream file = File.OpenRead(name);
data = new byte[SIZE];
file.Read(data, 0, SIZE);
file.Close();

byte b1 = data[0];
byte b2 = data[1];

if( (Convert.ToChar(b1) != 'B')
|| (Convert.ToChar(b2) != 'M'))
{
Console.WriteLine("not a BMP file");
return;
}

width = data[18] + (data[19]*256) + (data[20]*256*256) + 
(data[21]*256*256*256);

height = data[22] + (data[23]*256) + (data[24]*256*256) +
(data[25]*256*256*256);

Console.WriteLine("Width: {0} - Heigth: {1}", width, height);
}
}
catch(Exception)
{
Console.WriteLine("Error!!!");
}
}
}