Using the .NET Image Class

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:



Click here for a larger image.

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.




Comments

  • Thank!

    Posted by snun_r on 10/11/2004 11:08am

    good for source code.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds