2007-09-13
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 3 of 3 )
The BMP header information is helpful in some situations, but we'll ignore the data in it for now. All we really need to remember is that we have to skip the first 54 bytes of the image data before doing any processing. Not only is it a waste of time to operate on the header data, but when we restore the data back into the Bitmap object there will be many errors introduced.
The data comes in sets of four bytes for each pixel. The first byte is the blue value, the second the green, the third the red, and the fourth is an alpha value that some programs may or may not use.
I have to point out that this is not the format for all BMP files. This is just how the .NET runtime saves BMP files. There are lots of other ways that the data can be organized, including a palette-indexed system. But since the .NET runtime saves in the way that I've described, then we can simplify things by limiting our discussion to that particular format.
I'll start with the code for darkening and lightening the image. First, there's a helper method that adds a value to the current image data value. The value can be positive or negative. The helper method checks to make sure that the value isn't less than 0 or that it isn't greater than 255 since these are the far extremes of the RGB values. The ChangeData method follows.
byte ChangeData(byte DataValue, int AddValue)
{
if (AddValue + (int)DataValue > 255)
{
return (255);
}
else if (AddValue + (int)DataValue < 0)
{
return (0);
}
return( (byte)((int)DataValue+AddValue) );
}
There are two methods that are almost identical. One darkens (btnLess_Click) and one lightens (btnMore_Click). The only difference in these two methods is that one sends the value of -25 (to darken) to the ChangeData method, while the other sends the value of 25 (to lighten). Both methods can be seen here.
private void btnLess_Click(object sender, EventArgs e)
{
byte[] BitmapData = BitmapHelper.BitmapDataFromBitmap(m_objBitmap);
int nPixels = m_objBitmap.Width * m_objBitmap.Height;
for (int i=0; i<nPixels*4; i++)
{
BitmapData[54+i] = ChangeData(BitmapData[54+i], -25);
}
m_objBitmap = BitmapHelper.BitmapFromBitmapData(BitmapData);
Invalidate();
Update();
}
private void btnMore_Click(object sender, EventArgs e)
{
byte[] BitmapData = BitmapHelper.BitmapDataFromBitmap(m_objBitmap);
int nPixels = m_objBitmap.Width * m_objBitmap.Height;
for (int i=0; i<nPixels*4; i++)
{
BitmapData[54+i] = ChangeData(BitmapData[54+i], 25);
}
m_objBitmap = BitmapHelper.BitmapFromBitmapData(BitmapData);
Invalidate();
Update();
}
Conclusion
Once you get past the hurdle of getting started, image processing in C# is easy. In future articles, I'll use the same BitmapHelper class and then do some more interesting filtering.
![]() |
|


