Languages - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Languages arrow Page 3 - GDI+ Image Handling in C#
GDI+ Image Handling in C#
By Rick Leinecker

Rate This Article: Add This Article To:

GDI+ Image Handling in C# - ' Loading and Displaying Images'
( Page 3 of 3 )

Loading Images

The class that encapsulates an image is the Bitmap class. In order to load an image, you must use the Bitmap class's constructor. There are quite a few overrides, but I almost always use the constructor that takes a single argument specifying the file name as follows.

Bitmap objBitmap = new Bitmap("FileName.jpg");
ADVERTISEMENT

The Bitmap constructor throws a System.ArgumentException exception. I found this strange, though, as it throws this very same exception if the file doesn't exist. I would have thought there would have been other exceptions thrown that cover file I/O issues.

Once you have the image loaded, there are some very useful properties that the Bitmap class has to offer. The ones that I used most often are Width and Height. The following code loads an image and then displays its width and height in a message box.

Bitmap objBitmap = new Bitmap(strFileName);
string strInfo = "Width:" + objBitmap.Width +
    "Height:" + objBitmap.Height;
MessageBox.Show(strInfo);

You can also create a thumbnail version of the image with the Bitmap.GetThumbnailImage method. The following code shows how to load an image and then create a thumbnail that is 50 pixels wide by 50 pixels high.

Bitmap objBitmap = new Bitmap(strFileName);
Bitmap objThumbnailBitmap = objBitmap.GetThumbnailImage(50, 50, 
  null, null);

In the LearnImagesClass demo application, there are three images that are included in the project's debug directory. They are loaded in response to a change in the combo box that contains the image choices. The following code is a simplification of the actual code, but clearly shows how to load an image based on a user's selection.

m_objBitmap = new Bitmap(cmbImageList.SelectedItem + ".jpg");
Invalidate();
Update();

Displaying Images

Displaying images to the drawing surface is easy. It's simply a matter of using the Graphics.DrawImage override that's appropriate. The simplest override (which I use most often) has three arguments: the Bitmap object, the x coordinate, and the y coordinate. The following example shows how it can be used.

private void OnPaint(object sender, PaintEventArgs e)
{
    // m_objBitmap is a Bitmap object that has
    //   has already loaded the image file.
    e.Graphics.DrawBitmap(m_objBitmap, 0, 0);
}

Note that a Graphics object is necessary to render a Bitmap object to any canvas. The OnPaint method is fired in response to a system message (WM_PAINT if you remember your early windows messages). You can get a Graphics object from the application at any time, though, and draw an image without having to cause a window redraw as follows.

Graphics g = Graphics.FromHwnd(this.Handle);
// m_objBitmap is a Bitmap object that has
//   has already loaded the image file.
e.Graphics.DrawBitmap(m_objBitmap, 0, 0);

Scaling an image to the client area is easy. All you need to do is add two more arguments indicating the width and height of the area to which you want to draw. The following example shows how to draw to an area that's 400 pixels wide and 300 pixels high.

e.Graphics.DrawBitmap(m_objBitmap, 0, 0, 400, 300);

The demonstration application provides the option of scaling the loaded image or drawing it unscaled. The following code is a simplified version of what's in the application.

// Visual Studio created this method. It's
//   fired when the window needs to be repainted.
private void OnPaint(object sender, PaintEventArgs e)
{

     // Draw the image in the application
     //  client area.
     if (!chkScale.Checked)
     {
          // Draw the image unscaled.
          e.Graphics.DrawImage(m_objBitmap,
               0, 0);
     }
     else
     {
          // Draw the image scaled.
          e.Graphics.DrawImage(m_objBitmap,
               0, 0,
               ClientRectangle.Width, ClientRectangle.Height);
     }
}

The following two figures show the application rendering an image unscaled, and then scaled.

Creating And Drawing To Images

You can create a blank image very easily. This is handy when you have a set of complex drawing commands that take awhile to execute. Creating a Bitmap object, drawing the complex commands into it, and then rendering the Bitmap object instead of the set of complex drawing commands will make your application perform much better.

To create a blank bitmap, simple use the Bitmap constructor and specify the desired width and height as follows.

Bitmap objBitmap = new Bitmap(400, 300);

The newly-created bitmap is now ready to act as a canvas, but first you need a Graphics object. The Graphics.FromImage method is used to get a Graphics object from a bitmap as follows.

Graphics g = Graphics.FromImage(objBitmap);

The demonstration application draws to an in-memory bitmap. If the user clicks on the Create button, the application creates a new blank bitmap, draws a white rectangle into it, and takes any text in the text box and draws that into the bitmap. The following code is a helper method that performs the steps.

// This helper method creates a custom bitmap object,
//   makes it white, and then draws text from the
//   the text box into it.
void CreateCustomBitmap()
{
     // Create the custom bitmap based on the app client rectangle.
     m_objCustomBitmap = new Bitmap(ClientRectangle.Width,
        ClientRectangle.Height);
     // Get a graphics object from the bitmap.
     Graphics g = Graphics.FromImage(m_objCustomBitmap);
     // Fill the bitmap with a white rectangle.
     g.FillRectangle(new SolidBrush(Color.White), 0, 0,
          m_objCustomBitmap.Width, m_objCustomBitmap.Height);
     // Draw the text string into the bitmap.
     g.DrawString(txtCustomText.Text, new Font("Times New Roman", 35,
       FontStyle.Regular), new SolidBrush(Color.Black), 
       new RectangleF(0, 0, ClientRectangle.Width,
       ClientRectangle.Height));
}

Saving Images

Saving images is as easy as the other things we've talked about. The Bitmap.Save method lets you specify the destination filename and the file format as follows.

objBitmap.Save("MyFile.jpg", ImageFormat.Jpg);

One note, though, is that in order to use the ImageFormat enumeration you must add the following statement to the top of your code.

using System.Drawing.Imaging;

The demonstration application has a Save button that allows you to save the current image. The method from the application is shown here.

// Visual Studio created this method. It's
//   fired when the Save button is clicked.
private void btnSave_Click(object sender, EventArgs e)
{
     // If user selects the OK button, then we do stuff.
     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
          // First we set the image format with which we'll save.
          ImageFormat SelectedFormat = ImageFormat.Gif;
          if( rbtnJpg.Checked )
          {
               SelectedFormat = ImageFormat.Jpeg;
          }
          else if( rbtnPng.Checked )
          {
               SelectedFormat = ImageFormat.Png;
          }
          // Now save the image.
          m_objBitmap.Save(saveFileDialog1.FileName, SelectedFormat);
     }
}

Conclusion

The demonstration application can be downloaded here. It illustrates all of salient points of the article.

Using images in your applications are is easy. And it can really enhance their appearance tremendously.



 
 
>>> More Languages Articles          >>> More By Rick Leinecker
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.