Image Processing in C#


This application explains basic concepts of image processing including brightening, converting to gray and adding notes to an image using System.Drawing.Imaging namespace classes.

Following code shows how to display an image in a picture box.

private System.Windows.Forms.PictureBox p1;
string
path = abc.jpg;
p1.Image =
new
Bitmap(path);

This code show how to take the bitmap data:

Bitmap b = new Bitmap(path);
BitmapData bmData = b.LockBits(
new
Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

The screen shot above shows an image before and after increasing brightness.

This is the main function, where we do the main processing. If you look into the code you will notice, I am using unsafe code, where I am doing the main processing. This is really important because unsafe mode allow it to run that piece of code without CLR, which make the code to run much faster. Here its important because we care about the speed of the routine.

public static bool Brighten(Bitmap b, int nBrightness)
{
// GDI+ return format is BGR, NOT RGB.
BitmapData bmData
= b.LockBits(
new
Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int
stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe

{
int
nVal;
byte * p = (byte *)(void
*)Scan0;
int
nOffset = stride - b.Width*3;
int
nWidth = b.Width * 3;
for(int
y=0;y<b.Height;++y)
{
for (int
x = 0; x < nWidth; ++x)
{
nVal = (
int
) (p[0] + nBrightness);
if
(nVal < 0) nVal = 0;
if
(nVal > 255) nVal = 255;
p[0] = (
byte
)nVal;
++p;
}
p += nOffset;
}
}
b.UnlockBits(bmData);
return true
;

When you click on the Bright button this piece of code execute.

private void btnBright_Click(object sender, System.EventArgs e)
{
try
{
string
path = Path.Combine(tv1.SelectedNode.FullPath, lstFiles.SelectedItem.ToString());
Bitmap b =
new
Bitmap(path);
Brighten(b, m_nTrack);
p2.Image = b;
}
catch
{}
}

This next screen-shot shows the gray effect.


Similar Articles