Blue Theme Orange Theme Green Theme Red Theme
 
Dundas Dashboard
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » GDI+ & Graphics » Image Conversion Utility in C#

Image Conversion Utility in C#

This article describes a very easy approach to building an image conversion utility that will permit the user to open a supported image type and convert it to another supported image type.

Author Rank:
Technologies: .NET 1.0/1.1, GDI+, Windows Forms,Visual C# .NET
Total downloads : 1391
Total page views :  34828
Rating :
 3/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ImageConverter.zip
 
Become a Sponsor



Introduction: 

This article describes a very easy approach to building an image conversion utility that will permit the user to open a supported image type and convert it to another supported image type. The supported file types addressed in the application are:

  • Bitmap
  • Enhanced Windows Metafile
  • Exchangeable Image File
  • GIF Files
  • JPEG Files
  • PNG Files
  • TIFF Files
  • Window Metafiles

All file conversions are accomplished through the use of the Microsoft .NET 2.0 Imaging class library's conversion methods. In addition to demonstrating the approach used to achieve the file conversions, the application also demonstrates an approach used to open an image file into a picture box control.

Figure 1:  The Image Conversion Utility In Use

Getting Started:

In order to get started, unzip the attachment and load the solution into Visual Studio 2005. Examine the solution explorer and note the files contained in the project:

Figure 2:  The Solution Explorer Showing the Project Files

The contents of the solution show that it contains a single project entitled, "ImageConverter". This project contains a single form called "Form1". The Form1.vb class contains all of the code necessary to drive the utility.

A quick check of the references will reveal that only the default class libraries are contained in the project and the Program.cs file is a unedited version of the default version of that file.

The Code:  The Main Application Form.

The main application's form  class (Form1.vb) contains all of the application code needed to make the file conversions and to open a file into the application's image viewer (which is nothing more than a standard picture box control).

The class begins with the using statements; the imports include the standard and default inclusions as well as an added reference to System.Drawing.Imaging. The class declaration is equally simple:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Drawing.Imaging;

using System.Text;

using System.Windows.Forms;

 

namespace ImageConverter

{

    public partial class Form1 : Form

    {...

Following the class declaration and library imports, a few local variables are declared to support file management within the application across each of the class methods:

// local variable declarations

string CurrentFile;
Image img;

The string variable "CurrentFile" is used to store the name of the current, working image file (as loaded into the form's picture box). The image variable "img" is used to provide form level exposure to the current image; this was done here to make the image available to any of the form method calls that require access to the image.

Following the variable declarations, there is a section of default code added to the project through the Visual Studio IDE. You may examine that code from the IDE if you so desire but it won't be discussed in this article.

The next piece of code worthy of mention is the code used to open an image file and load it into the form. It is not really necessary to load the file in order to perform the conversion, however, this utility does load the file so the user may examine it prior to making the conversion. The code for the file open method looks like this:

// Show open file dialog to allow user to open an image file

// for display in the application

private void openToolStripMenuItem_Click(object sender, EventArgs e)

{

    openFileDialog1.Title = "Open Image File";

    openFileDialog1.Filter = "Bitmap Files|*.bmp" +

        "|Enhanced Windows MetaFile|*.emf" +

        "|Exchangeable Image File|*.exif" +

        "|Gif Files|*.gif|Icons|*.ico|JPEG Files|*.jpg" +

        "|PNG Files|*.png|TIFF Files|*.tif|Windows MetaFile|*.wmf";

    openFileDialog1.DefaultExt = "bmp";

    openFileDialog1.FilterIndex = 1;

    openFileDialog1.FileName = "";

    openFileDialog1.ShowDialog();

 

    if (openFileDialog1.FileName == "")

        return;

 

    CurrentFile = openFileDialog1.FileName.ToString();

 

    img = Image.FromFile(openFileDialog1.FileName);

    pictureBox1.Image = img;

}

This method first configures and displays a File Open dialog; from the dialog, the user may navigate to the file they intend to convert. The method checks to see if a valid file name has been entered and, if no valid file name exists, the application will abort the attempt and close the dialog box.

If a valid file has been selected, the method will set the current file name variable to the file name in the file open dialog box and will set the "img" variable to contain the image using the Image.FromFile method included in the imaging library. With a file loaded, you should see the selected image loaded into an picture box control on the form.

Once the image has been loaded, the user may open the file menu, select "Convert To" and then select one of the alternative image file formats:


 
Figure 3:  Convert to Alternative Image File Format Options

When the user selects one of the available image options, the application will launch a method used to complete the conversion; the application will not overwrite an existing file nor will it allow the user to specify a new file name or location. The converted file will be dropped into the same folder as the original but will carry the new file extension:

Figure 3:  Windows Explorer showing original and converted files in the same directory (note the Size and Type values to verify the conversion has occurred).

Whilst the code used to make the conversion is, in the application, specific to the target image type, very little in each block of code changes. Since all of the conversion code is essentially the same, I will only show one of the methods here, you can refer to source code to see each specific conversion:

// Convert to GIF

private void gIFFileToolStripMenuItem_Click(object sender, EventArgs e)

{

       string newName = 

       System.IO.Path.GetFileNameWithoutExtension(CurrentFile);

       newName = newName + ".gif";

 

       try

       {

           img.Save(newName, ImageFormat.Gif);

       }

       catch

       {

           MessageBox.Show("Failed to save image to GIF format.", "Error",

           MessageBoxButtons.OK, MessageBoxIcon.Error);

           return;

       }

 

       MessageBox.Show("Image file saved to " + newName.ToString(), "Image

       Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

The code shown here is the call made to convert the current image to GIF format. At the start of the method, a new string variable is declared and used to capture the name of the current file without the current file's extension. The new name variable then has the file extension of the new, converted file type added to it.

Once the new file name has been configured, the existing image, made available through the "img" variable, has its' Save method evoked, the new file name and the desired image format are passed to this Save method. The Imaging library function then does the work of converting the image to the target format and saving it into the directory along with the original version of the image.

If the conversion does not take place (for example if the user tries to overwrite the original file), a message box will be displayed to tell the user that the requested conversion did not occur. If the Save occurs without error, the user is told that the image file was saved to the new file name. That is all there is to it. If you check your image file directory, you will see the original and the converted file, each with the correct extension.

Summary.

This application has attempted to describe how simple it is to accomplish an image file format conversion through the use of the .NET 2.0 framework's Imaging class. Whilst this document addresses the topic in the context of a C# 2005 application; there is no reason that you could not apply the same code to a 1.0 or 1.1 framework based solution if you are working in .NET or .NET 2003.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ImageConverter.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
metafiles cannot be created using the image.Save by TJM On July 21, 2007
It should be noted that metafiles cannot be created using the image.save method. See Microsoft's documentation regarding the save function. PNGs are actually returned instead. -Tod
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved