Click here to Skip to main content
Click here to Skip to main content

How to Load/Display images with C#

, 20 Jul 2003
Rate this:
Please Sign up or sign in to vote.
How to load/display images in a form in C#, explained with the code of a complete image viewer application

Sample Image - maximum width is 600 pixels

Issues covered

This article explains how to:

  • Display .NET framework supported image types (JPG, JPEG, GIF, PNG, TIF...) into a form.

In addition, the code covers:

  • Accessing the Registry (creating, writing, retrieving registry key values).
  • Using WinForm controls like StatusBar, ToolBar, MainMenu, ImageList, Timer and, OpenFileDialog.
  • Processing command-line arguments.
  • To obtain the list of files in a directory.
  • To create a Windows Application setup project

Introduction

You always need to access images for some reason or the other. When you have the .NET framework SDK with you, you needn't bother to buy other applications for that job - develop one for yourself! With the supremely rich .NET framework, manipulating images is very simple. This article places emphasis only on how to display images. The code on the other hand, involves a lot of other stuff including a setup, which were used to implement a number of standard features seen in popular applications. They are quite straight forward; so you could understand them by yourself.

Apart from the usual set, this application uses the following namespaces too:

  • System.Drawing - For displaying images
  • System.Drawing.Drawing2D - For displaying images
  • Microsoft.Win32 - For accessing the registry

The code explained

To load images (technically 'draw'), you use any one of the 30 overloads of: System.Drawing.Graphics.DrawImage(...).

As is evident, DrawImage() is a method of the Graphics class. So, before using DrawImage() straightaway, you need to create a Graphics object. This Graphics object would be of the form you are going to draw the image onto. Typically, you create this object in the Paint Handler of the form. An example for a Paint Handler is:

private void MainForm_Paint(object sender, <BR>                           System.Windows.Forms.PaintEventArgs e)<BR>{<BR>    ...<BR>}
When someone calls a form's paint handler, some data regarding the form's graphics stuff is passed to it. This data is held in the PaintEventArgs object, in this case, the object e. This object has a property Graphics - and that's exactly what we want. You just use it to initialize your own Graphics object, like this:
Graphics g = e.Graphics;

So, now that you have a Graphics object, you could call the DrawImage() method. But wait, what about the arguments? That's what we are going to see. The overload I will discuss here is:

public void DrawImage(<BR>  Image image,<BR>  RectangleF rect<BR>);

This method draws the specified Image object (System.Drawing.Image), at the specified location and with the specified size (passed implicitly through the RectangleF object - rect). An Image object holds the actual image data that is to be drawn. And with little thinking, you could easily understand that with a RectangleF object you could define both the size and position of the image.

So how do we develop these arguments?

System.Drawing.Image is an abstract class, designed to act as the base for System.Drawing.Bitmap and System.Drawing.Imaging.Metafile. What we are interested in is System.Drawing.Bitmap. We create an Image object using the Bitmap class, like this:

 MyBitmap = new Bitmap(...);
There are 12 overloads for the Bitmap constructor. The one I will discuss here is:
public Bitmap(<BR>  string filename<BR>);

You just need to pass the path to the image file you want to load. And then, you have the initialized Image object. What remains is the RectangleF object which you could initialize as you wish. Once done, call the DrawImage() method, and there you are, you have done it!

An example code listing for the actions discussed above:

private void MainForm_Paint(object sender, <BR>                            System.Windows.Forms.PaintEventArgs e)<BR>{<BR>    ...<BR>        ...<BR>    Graphics g = e.Graphics;<BR>        MyBitmap = new Bitmap("c:\\image.bmp");<BR>    g.DrawImage( MyBitmap, new RectangleF(MyPoint.X, MyPoint.Y, <BR>                 MyBitmap.Width*(fScale), MyBitmap.Height*(fScale)) );<BR>    ...br>    ...<BR>}

Code for the additional features

This section discusses the way the rest of the application is designed. Since an exhaustive explanation would be beyond the scope of this article, I would only give you a brief description of the regions used. Read the code, read this description; and you would understand (hopefully). Here goes:

The My Vars Declaration region declares all the variables that are used. These variables are sub-divided according to their functionality. Some of these are initialized to their default values in the declaration itself.

The App Main Entry region encapsulates the application Main function as well as the main form constructors. When the app is executed, the Main function determines whether there are any command-line arguments [file to be displayed], and invokes the required overloaded main form constructor, passing the argument if necessary. The main form constructor, would then set the current directory to that of the argument in case there exists one. It also sets the szRequestedFile variable to the argument value.

The Main Form Load region consists of the main form load function, which calls the GetRegistrySettings function to retrieve values from the current user's registry, makes sure that the timer is not on, initializes the FileTypes ArrayList, sets all the from controls to the registry values by calling the SetControlsToRegistrySettings function, processes the current folder by calling the ProcessDirectory function, and displays the image if necessary in either the normal mode or the slide show mode.

The Main Form Paint Handler region comprises of the most complicated and used function in the app - the paint function. This function starts by setting the status bar text to Working..., proceeds to initialize a Graphics object, sees whether the 'size to fit' option is true or false, determines the position where the image is to displayed, draws it, and finally sets the status bar text to Ready .

The Main Form Paint Handler region consists of a number of functions designed for different activities.

  • GetRegistrySettings gets the current user's registry settings from the registry and initializes the registry variables.
  • SetControlsToRegistrySettings resets the form controls so as to set it to the current user's settings.
  • SetSize resizes the form according to the current Image's size.
  • ProcessDirectory finds out all the images within the current folder and initializes FileArray.
  • GetFilePath get's the currently selected file's path from FileArray.
  • SetPicture sets variables to the selected file's attributes and invokes the paint handler.

The EventHandlers region consists of handlers for the menu events, toolbar events, mouse move event, form resize event as well as the timer elapsed event. Each of these events call the DoAction function to carry out the required function if appropriate.

The DoAction function lies within the Do Action Handler region. This function incorporates all the possible actions that would be invoked within this app. This function was developed in order to reduce redundant code that would have to be coded for both the toolbar as well as the main menu. Plus this model reduces complexity.

For the experimentalist: in case you ever want to add more features, follow these simple steps:

  • In the My Vars Declaration region, add the required variables in the specific section. This is to make matters organized.
  • Expand the Do Action Handler region. Within the list of existing cases, add a new one defining the action to be carried out.
  • When an event occurs where the new action is to be executed, call DoAction passing the name of the action just defined.

Conclusion

This is a very simple application with a simple design and simple architecture. But it works! And that's exactly what we want.

Happy programming...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rakesh Rajan
Web Developer
India India
Rakesh Rajan is a Software Engineer from India working at Technopark, Trivandrum in Kerala. He is a Microsoft MVP and an MCSD (.NET) with a few other certifications, and had been working in .NET for the past 3 years. He graduated majoring in Computer Science during his memorable days at Ooty (a wonderful hill station in Southern India). You can find him posting at newgroups, writing articles, working on his own projects or taking some time off by listening to music by Enya or Yanni, or reading an Archer or Sheldon.
 
Find his online publications here.
 
Rakesh blogs at http://rakeshrajan.com/blog/ and maintains a site http://rakeshrajan.com/.
He used to blog at http://www.msmvps.com/rakeshrajan/.
 
Drop him a mail at rakeshrajan {at} mvps {dot} org.

Comments and Discussions

 
QuestionPicture box Pinmemberagprathiba8-Jun-11 6:29 
GeneralMy vote of 1 Pinmemberswapan jana18-Jan-11 20:01 
GeneralUseful component to handle images PinmemberMaxDDD8-Jul-09 21:31 
QuestionPossible to see a multipage tiff? Pinmembergator30216-Aug-06 10:54 
GeneralNice Piece of code. However... Pinmemberlatmask22-Jan-06 9:56 
GeneralRe: Nice Piece of code. However... PinmemberRakesh Rajan23-Jan-06 14:33 
QuestionCan we load dwg &amp; dwf file of autocad in this application Pinmembertejasjunior1-Jan-06 21:14 
GeneralMoving a bitmap file in picture box PinmemberFelix_mca11-Jul-05 4:52 
GeneralMoving a bitmap file in picture box PinmemberFelix_mca11-Jul-05 4:44 
Generalplacing images and change the color of image Pinmembersenpost12-Dec-04 16:41 
GeneralRe: placing images and change the color of image PinmemberRakesh Rajan13-Dec-04 3:50 
GeneralProblems with Tiff-Images in high resolutions Pinmembertonictickle8-Mar-04 8:46 
GeneralRe: Problems with Tiff-Images in high resolutions PinmemberRakesh Rajan9-Apr-04 22:40 
GeneralDisable the 'Size images to fit window' feature plz PinmemberRakesh Rajan22-Jul-03 19:20 
GeneralRe: Disable the 'Size images to fit window' feature plz Pinmemberartxb27-Sep-04 20:43 
GeneralRe: Disable the 'Size images to fit window' feature plz PinmemberRakesh Rajan28-Sep-04 4:31 
GeneralRe: Disable the 'Size images to fit window' feature plz PinmemberSocalHack30-Nov-04 9:59 
GeneralRe: Disable the 'Size images to fit window' feature plz PinmemberRakesh Rajan30-Nov-04 13:53 
GeneralRe: Disable the 'Size images to fit window' feature plz PinmemberSaysa7-Apr-09 19:41 
GeneralCrashes on loading PinmemberFurty24-Feb-03 9:59 
GeneralRe: Crashes on loading PinmemberRakesh Rajan25-Feb-03 0:55 
GeneralRe: Crashes on loading PinmemberRakesh Rajan25-Feb-03 4:46 
GeneralRe: Crashes on loading PinmemberFunnyButCocky27-Feb-03 16:38 
GeneralRe: Crashes on loading Pinmember00strange1-Oct-07 19:30 
GeneralRe: Crashes on loading Pinmemberkuku_banna25-Mar-10 2:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140718.1 | Last Updated 21 Jul 2003
Article Copyright 2003 by Rakesh Rajan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid