Click here to Skip to main content
15,883,705 members
Articles / Programming Languages / C#
Article

How to Load/Display images with C#

Rate me:
Please Sign up or sign in to vote.
4.22/5 (30 votes)
20 Jul 20036 min read 740.5K   26.4K   87   28
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:

C#
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:
C#
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:

C#
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:

C#
MyBitmap = new Bitmap(...);
There are 12 overloads for the Bitmap constructor. The one I will discuss here is:
C#
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:

C#
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


Written By
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

 
AnswerMessage Closed Pin
16-Sep-14 1:44
Member 1093923116-Sep-14 1:44 
QuestionPicture box Pin
agprathiba8-Jun-11 6:29
agprathiba8-Jun-11 6:29 
GeneralMy vote of 1 Pin
swapan jana18-Jan-11 20:01
swapan jana18-Jan-11 20:01 
GeneralUseful component to handle images PinPopular
MaxDDD8-Jul-09 21:31
MaxDDD8-Jul-09 21:31 
QuestionPossible to see a multipage tiff? Pin
gator30216-Aug-06 10:54
gator30216-Aug-06 10:54 
GeneralNice Piece of code. However... Pin
latmask22-Jan-06 9:56
latmask22-Jan-06 9:56 
GeneralRe: Nice Piece of code. However... Pin
Rakesh Rajan23-Jan-06 14:33
Rakesh Rajan23-Jan-06 14:33 
QuestionCan we load dwg &amp; dwf file of autocad in this application Pin
tejasjunior1-Jan-06 21:14
tejasjunior1-Jan-06 21:14 
GeneralMoving a bitmap file in picture box Pin
Felix_mca11-Jul-05 4:52
Felix_mca11-Jul-05 4:52 
GeneralMoving a bitmap file in picture box Pin
Felix_mca11-Jul-05 4:44
Felix_mca11-Jul-05 4:44 
Generalplacing images and change the color of image Pin
senpost12-Dec-04 16:41
senpost12-Dec-04 16:41 
GeneralRe: placing images and change the color of image Pin
Rakesh Rajan13-Dec-04 3:50
Rakesh Rajan13-Dec-04 3:50 
Question #1: You can make use of the Rectangle.Contains method.
Question #2: You can use GDI classes for these, mainly the ColorMatrix type.

HTH,


Rakesh

GeneralProblems with Tiff-Images in high resolutions Pin
tonictickle8-Mar-04 8:46
tonictickle8-Mar-04 8:46 
GeneralRe: Problems with Tiff-Images in high resolutions Pin
Rakesh Rajan9-Apr-04 22:40
Rakesh Rajan9-Apr-04 22:40 
GeneralDisable the 'Size images to fit window' feature plz Pin
Rakesh Rajan22-Jul-03 19:20
Rakesh Rajan22-Jul-03 19:20 
GeneralRe: Disable the 'Size images to fit window' feature plz Pin
artxb27-Sep-04 20:43
artxb27-Sep-04 20:43 
GeneralRe: Disable the 'Size images to fit window' feature plz Pin
Rakesh Rajan28-Sep-04 4:31
Rakesh Rajan28-Sep-04 4:31 
GeneralRe: Disable the 'Size images to fit window' feature plz Pin
SocalHack30-Nov-04 9:59
SocalHack30-Nov-04 9:59 
GeneralRe: Disable the 'Size images to fit window' feature plz Pin
Rakesh Rajan30-Nov-04 13:53
Rakesh Rajan30-Nov-04 13:53 
GeneralRe: Disable the 'Size images to fit window' feature plz Pin
Saysa7-Apr-09 19:41
Saysa7-Apr-09 19:41 
GeneralCrashes on loading Pin
Furty24-Feb-03 9:59
Furty24-Feb-03 9:59 
GeneralRe: Crashes on loading Pin
Rakesh Rajan25-Feb-03 0:55
Rakesh Rajan25-Feb-03 0:55 
GeneralRe: Crashes on loading Pin
Rakesh Rajan25-Feb-03 4:46
Rakesh Rajan25-Feb-03 4:46 
GeneralRe: Crashes on loading Pin
FunnyButCocky27-Feb-03 16:38
FunnyButCocky27-Feb-03 16:38 
GeneralRe: Crashes on loading Pin
00strange1-Oct-07 19:30
00strange1-Oct-07 19:30 

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

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