Microsoft & .NETVisual C#Using the .NET Image Class with Managed C++

Using the .NET Image Class with Managed C++

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

From Kate Gregory’s Codeguru column, “Using Visual C++ .NET“.

In an earlier column, I showed you how to use the ATL CImage class to dramatically simplify working with images in Classic C++ applications. This time around, I’ll create the same application as a Managed C++ Windows application and use System.Drawing.Image to do the heavy lifting. Because Visual Studio .NET 2003 (formerly known as Everett) supports C++ Windows applications, that’s what I’m using here. You can create a Windows application with the release version of Visual C++ using the steps of my earlier column if you don’t have access to the beta version of Visual Studio .NET—or become an MSDN subscriber so you always get the latest goodies.

Here’s a simple application that displays and converts images:

This is an ordinary .NET Windows application. I added a textbox, two buttons for “Load” and “Save As JPG,” a picture control, and another button for “Done.” Controls have Text and Name rather than Caption and ID, and names don’t start with IDC_, so if you haven’t been doing any work in VB or C#, you’ll feel a little lost. Here’s how things look in the dialog editor:

Because this is a .NET Windows application, the designer has added all the variables I might need to work with, created the class I need, and so on. I used the Properties Window to disable the “Save As JPG” button by default (there’s code later to enable it). I also changed properties of the picture box: I set the background to Window (which is white by default) rather than Control (which is gray by default) and changed the SizeMode property to CenterImage. Then I just double-clicked the Load button to edit the handler. Here’s how that code looks:

private:
  System::Void Load_Click(System::Object * sender,
          System::EventArgs * e)
  {
    if (filename->Text == "")
      filename->Text = "Please enter a file name first";
    else
    {
      try
      {
        image = System::Drawing::Image::FromFile(filename->Text);
        pictureBox1->Image = image;
        Save->Enabled = true;
      }
      catch (System::Exception* e)
      {
        // out of memory exception thrown for bad format
        MessageBox::Show("File not found or invalid format");
      }
    }
  }

One of the things I like about this code, compared to my earlier MFC version, is that I don’t need to call UpdateData() or Invalidate()—the framework takes care of these things for me.

In any .NET application, error checking is done by exceptions rather than checking return values. The documentation says that FromFile() throws an OutOfMemoryException when the format is bad, but because the file might not even exist, I just catch any and all exceptions. You could split this into different catch statements with different error messages if you wanted to.

What about converting a GIF to a JPEG? All you have to do is save the image and specify the format. Here’s how to do it:

private:
  System::Void Save_Click(System::Object *  sender,
          System::EventArgs *  e)
  {
    String* savefilename = String::Concat(
      filename->Text-<Substring(0,filename->Text->IndexOf('.')),
      ".JPG");
    image->Save(savefilename, System::Drawing::Imaging::
           ImageFormat::Jpeg);
  }

Two lines of code! How hard is that?

When I built this application in MFC, I got an OK handler written for me that closed the dialog. My .NET Windows application doesn’t get that, so I added my own handler for the Done button:

private:
  System::Void Done_Click(System::Object * sender,
                          System::EventArgs * e)
  {
         this->Close();
  }

What else can you do with a Image object? How about making thumbnails with GetThumbnailImage()? You can also draw directly on the image. First create a Graphics object, load the image into it, and then draw on the Graphics object with the pen or brush of your choice. All of GDI+ is at your disposal, so why not start tinkering and see what you can do?

About the Author

Kate Gregory is a founding partner of Gregory Consulting Limited (www.gregcons.com). In January 2002, she was appointed MSDN Regional Director for Toronto, Canada. Her experience with C++ stretches back to before Visual C++ existed. She is a well-known speaker and lecturer at colleges and Microsoft events on subjects such as .NET, Visual Studio, XML, UML, C++, Java, and the Internet. Kate and her colleagues at Gregory Consulting specialize in combining software develoment with Web site development to create active sites. They build quality custom and off-the-shelf software components for Web pages and other applications. Kate is the author of numerous books for Que, including Special Edition Using Visual C++ .NET.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories