Introduction
This is my first post. I wrote this code when I was learning binary file I/O in C#. This code is not accurate because it displays an inverted image of a bitmap file. I hope this article will help someone learn C#. This code is not optimised, it is just for beginners learning to work with files.
Background
Bitmap file: This file contains the pixel data we want to read and display. Here is structure of a bitmap file specified in MSDN:
Structure Corresponding bytes
BITMAPFILEHEADER 0x00 0x0D
BITMAPINFOHEADER 0x0E 0x35
RGBQUAD array 0x36 0x75
Color-index array 0x76 0x275
Color data is stored from the 0x76 byte.
BIT Manipulation
In bitmap 1 byte stores two colors, i.e., first 4 bits contain one color and the last 4 contain another color.
Now to extract to the color from the byte. We have to shift the byte. To extract left 4 bits from the byte, just right shift it by 4 bits.
Now we get the required value from the byte. To extract the right 4 bits from the byte, we should left shift it by 4 bits.
This byte does not give the desired value so we again right shift the 4 bits.
Now we get the required value in the byte.
Code
First open Visual Studio and create a new Windows app in C#. In the form, add a picturebox
and a button
.
Now double click and write the following code:
private void button1_Click(object sender, EventArgs e)
{
Color bitcolor;
Bitmap image = new Bitmap(32, 32);
FileStream file = new FileStream("face.bmp", FileMode.Open, FileAccess.Read);
file.Seek(0x76, 0);
byte bhigh, blow;
int tmp;
for (int i = 0; i < 32; i++)
{
for (int j = 0; j < 32 ; j += 2)
{
tmp = file.ReadByte();
bhigh = (byte)(tmp >> 4);
blow = (byte)(tmp << 4);
blow = (byte)(blow >> 4);
bitcolor = getcolor(bhigh);
image.SetPixel(j, i, bitcolor);
bitcolor = getcolor(blow);
image.SetPixel(j+1 ,i, bitcolor);
}
}
this.pictureBox1.Image = image;
}
Now the method which will help us to retrieve our color:
public Color getcolor(byte a)
{
switch (a)
{
case 0: return Color.Black;
break;
case 1: return Color.DarkRed;
break;
case 2: return Color.DarkGreen;
break;
case 3: return Color.Yellow;
break;
case 4: return Color.Blue;
break;
case 5: return Color.Cyan;
break;
case 6: return Color.DarkGray;
break;
case 7: return Color.LightGray;
break;
case 8: return Color.LightGreen;
break;
case 9: return Color.LightPink;
break;
case 10: return Color.HotPink;
break;
case 11: return Color.Silver;
break;
case 12: return Color.Gold;
break;
case 13: return Color.Turquoise;
break;
case 14: return Color.Violet;
break;
case 15: return Color.White;
break;
default: return Color.Coral;
}
}
Bugs
I don't know why the image shows upside down. If you know, please tell me.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.