The .NET Frameworks uses GDI+ to handle graphics, and boy oh boy, there sure are a lot of classes to pick from. In order to play with some image manipulation, I was looking for a simple way to get an image on to a form and I spent a little time trying to work out the best approach.

 

The solution I ended up with was to create a PictureBox control on my form – yup, just drag it over from the toolbox. It’s easy to assign a default image to the PictureBox control, but I also wanted to access the bitmap that it was displaying.

 

The simplest way I found was to create a bitmap object,  and then tell the PictureBox control to use that bitmap as its display. So any changes I would make to the bitmap would be displayed by the PictureBox. Here’s how to define the bitmap and display it:

 

original_bitmap = new Bitmap(600,600);

pictureBox.Image = original_bitmap;

 

And here’s how to go through the bitmap pixel by pixel and change all the colors to grey:

 

public void GreyFilter()

{

 

   Color pixel;

      int t;

     

   for (int y=0; y<original_bitmap.Height; y++)

      {

            for (int x=0; x<original_bitmap.Width; x++)

            {

                  pixel = original_bitmap.GetPixel(x,y);

                  t = (pixel.R +pixel.G + pixel.B)/3;

                  original_bitmap.SetPixel(x,y,Color.FromArgb(t,t,t));

            }

      }

   pictureBox.Update();

}

 

 

There was one little catch – although it was possible to set and get pixel values from the bitmap (using GetPixel and SetPixel), I wanted to draw onto the bitmap using the Ellipse and other GDI+ methods. If you try the code above, you’ll see that the bitmap object only provides those two pixel methods. To do more, I had to create a Graphics object and use that. Here’s how I created a Graphics object associated with that bitmap:

 

Graphics G = Graphics.FromImage(original_bitmap);

G.FillEllipse(...);

pictureBox.Update();

G.Dispose();

 

And that was that.

 

I also wanted the PictureBox to contain an initial image – one taken from a resource that would be part of the final exe file. They way I did that was to important the image file into the Visual Studio project, make sure it was marked as an embedded resource and use some code to import and assign it to the PictureBox (and make sure it existed in the bitmap too):

 

System.Reflection.Assembly thisExe;

thisExe = System.Reflection.Assembly.GetExecutingAssembly();

System.IO.Stream file  = thisExe.GetManifestResourceStream("SharpPaint.sharppaintlogo.bmp");

Original_bitmap = new Bitmap(Image.FromStream(file));

pictureBox.Image = original_bitmap;