Managed C++: Loading and Displaying Images

One of the biggest drawbacks of programming in Visual C++/MFC was its lack of support for even the most basic of imaging functions—such as loading and displaying an image. Therefore, this article illustrates how incredibly easy .NET makes displaying a user-selected image and allowing the user to dynamically resize that image.

The File Open Dialog

The following figure shows the accompanying demo for this article. As you can see, the user can select an image file to display:

As opposed to MFC, where you instantiate and use a CFileDialog class, using the Windows Forms version of the common file open dialog involves these steps:

  1. From the form's designer, open the Toolbox and then drag and drop the OpenFileDialog control on the form. An icon will appear below the form and the control's ID will be automatically named. One advantage to this type of programming is that you can set its properties (such as InitialDirectory, Filter, and so on) in the designer instead of in code.
  2. Specify the OpenFileDialog control's properties. Below, I copied and pasted the portion of the demo code that sets the initial directory that will be displayed when the open file dialog displays, the filter list (the available options in the dialog's filter combo box), and the filter index.

    The OpenFileDialog::Filter property is a string that represents the types listed in the File Types combo box when the dialog is displayed. Each type is represented by a pair of values delimited by a vertical bar where the first value is the text that the user will see and the second value is the filter that the dialog will use in determining which files to display. Here are some examples to illustrate my point:

    Only display GIF files
    "GIFs (*.gif)|*.gif"
    
    Two filters--GIF and JPG
    "GIFs (*.gif)|*.gif|JPEGs (*.jpg)|*.jpg;*.jpeg"
    
    One combined filter (GIF and JPG)
    "GIF & JPG (*.gif;*.jpg;)|*.gif;*.jpg;"
    

    The FilterIndex property is used to specify which of the filters is the default.
    Note: Because index values in C++ are always relative to 0, C++ programmers naturally think to set the FilterIndex property to a value of 0 when they want the first element. However, don't be fooled. Whereas setting the value to 0 will select the first entry, that's only because any invalid index value defaults to the first entry. To correctly specify the index value, you must state it relative to 1 (in other words, 1 is the first entry—not 0).
    Here's the code pasted from the demo where the user is allowed to specify an image file to open. As you can see, the OpenFileDialog::ShowDialog is used to display the dialog and the return value is DialogResult::OK if the user selected a file (as opposed to canceling the dialog):
    dlgOpenFile->InitialDirectory = S"C:\\";
    
    dlgOpenFile->Filter =
      S"All Image Formats (*.bmp;*.gif;*.jpg;*.jpeg;*.tif)|"
      S"*.bmp;*.gif;*.jpg;*.jpeg;*.tif|"
      S"Bitmaps (*.bmp)|*.bmp|"
      S"GIFs (*.gif)|*.gif|"
      S"JPEGs (*.jpg)|*.jpg;*.jpeg|"
      S"TIFs (*.tif)|*.tif";
    
    dlgOpenFile->FilterIndex = 1;
    
    if (DialogResult::OK == dlgOpenFile->ShowDialog()) 
    {
      // Display the image
    }
    

Displaying an Image on a PictureBox Control

Once the user has selected a file using the OpenFileDialog, its FileName property (or FileNames if you specified to allow a multi-file selection) will contain the name of the selected file. Loading the image is as simple as calling the static Image::FromFile method. The following snippet sets the PictureBox::Image property to the Image object returned from Image::FromFile:

picImage->Image = Image::FromFile(dlgOpenFile->FileName);

Sizing an Image Within a PictureBox Control

You can use four basic values for displaying an image. You can specify this value in the designer (via the PictureBox control's SizeMode property) or in code if you want the user to be able to dynamically control this settings (as the demo illustrates).

  • Normal—Displays the image from the top-left corner of the PictureBox. If the image is smaller than the PictureBox, the image is displayed and the rest of the PictureBox is simply left blank. If the image is too large to be fully displayed, the image is cropped on its right and bottom sides.
  • Autosize—This value causes the PictureBox control to automatically resize itself to fit the image. If the PictureBox becomes too large for the form, it is cropped unless you specify a Form::AutoScroll value of true (in which case, the form will automatically display scrollbars).
  • Center—As the name implies, this value centers the image relative to the center of the PictureBox control.
  • Stretch—This will autosize the image to fit the horizontal and vertical size of the PictureBox control.
Note: If you allow the user to switch between sizing modes, you need to be aware of the fact that once you specify the Autosize mode (where the PictureBox control resizes itself to conform to the image's size), you'll need to reset the PictureBox::Width and PictureBox::Height properties when switching to any of the other modes.


About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

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

Top White Papers and Webcasts

  • This IDC study assists senior IT leaders in assessing the current state of their hybrid cloud management processes, governance models, technologies, and skills to identify gaps and create a road map for better aligning the organization's management model and tools with the emerging needs of complex, dynamic self-service hybrid cloud environments. This IDC MaturityScape identifies five maturity stages for hybrid cloud management based on a set of specific people, process, and technology dimensions and outcomes. …

  • Driven by the need for greater productivity and lower costs, enterprises around the globe are moving their applications to the cloud. This application note describes networking challenges that cloud-enabled enterprises face in today's digital economy, and the top reasons why intelligent optical networks are becoming critical to their success, with a direct impact on productivity and the ability to compete for long-term business success.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date