C#
  Home arrow C# arrow Page 3 - Lossless Image Converting in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Lossless Image Converting in C#
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2008-02-13

    Table of Contents:
  • Lossless Image Converting in C#
  • First Things First
  • The Real Thing
  • Taking a Break

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Lossless Image Converting in C# - The Real Thing


    (Page 3 of 4 )

    Now the time has come for us to cover the "real thing." That is, writing the required subroutines and functions that accomplish our goal - image conversion. You could see that previously we hid all of the components excluding the SelectPicture and Quit buttons. Clicking on btnQuit is self-explanatory. It contains nothing but this.Close(). So let's see what happens once we click on btnSelectPicture.

    private void btnSelectPicture_Click(object sender,System.EventArgs e)

    {

       if (SelectPicture.ShowDialog() == DialogResult.OK)

       {

           picThumbnail.Image = Image.FromFile(SelectPicture.FileName);

           this.Text = String.Concat("Lightweight Image Manipulation (" + SelectPicture.FileName + ")");

       }

       this.lbl_extension.Show();

       this.btnConvert.Show();

       this.ComboBox1.Show();

    }

    The above code makes our SelectPicture component appear so we can look for the location of our source image. Once we've found it and clicked on OK, that 'if' condition becomes validated and the thumbnail image appears. Oh, and speaking of picThumbnail - we have set its SizeMode to StretchImage.

    We move on to change the title of our form to visually point out that we have loaded the source image file. After this, we display our components because we can use them from now on - lbl_extension, btnConvert, ComboBox1. Speaking of ComboBox1, I added the following data items: BMP, JPG, GIF, and PNG, each in a new line.

    At this time, all that's left for us to see is what happens when we click btnConvert.

    private void btnConvert_Click(object sender, EventArgs e)

    {

       if (ComboBox1.SelectedIndex != -1)

       {

           string newExtension = (string)ComboBox1.SelectedItem;

           switch (newExtension.ToUpper())

           {

              case "GIF": saveFileDialog1.Filter = "Graphics Interchange Format (*.gif)
    |*.gif"; break;

              case "BMP": saveFileDialog1.Filter = "Bitmap Format (*.bmp)|*.bmp"; break;

              case "JPG": saveFileDialog1.Filter = "Joint Photographic Experts Group
    Format (*.jpg)|*.jpg"; break;

              case "PNG": saveFileDialog1.Filter = "Portable Network Graphics Format
    (*.png)|*.png"; break;

           }

           this.saveFileDialog1.ShowDialog();

       }

       else

           MessageBox.Show("Please select the desired extension format!", "Select
    Extension", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    The algorithm, in plain English, goes like this: we examine whether ComboBox1 is empty or not. If it's not, then the IF condition gets validated and we enter. We grab the selected extension and examine it through a switch. For each extension, we set the appropriate filters for saveFileDialog1. After this, we can just make it appear. If the user didn't select an extension at the combobox, then we display an error message-box.

    Now we need to cover the code that gets executed as soon as our saveFileDialog1 receives a click on OK. That is, the destination path was selected and we are ready to convert! Here we go now. It's quite short and straightforward.

    private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)

    {

       string newExtension = (string)ComboBox1.SelectedItem;

       string newName = saveFileDialog1.FileName;

       Image img = Image.FromFile(SelectPicture.FileName);

       saveFile(img, newName, newExtension);

    }

    The last code snippet is the saveFile method that we created. It does all the work!

    private void saveFile(Image img, string NewFileName, string NewFileExtension)

    {

       EncoderParameters codecParams = new EncoderParameters(1);

       codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

       ImageCodecInfo[] encoders;

       encoders = ImageCodecInfo.GetImageEncoders();

       bool success; success = false;

       try

       {

           switch (NewFileExtension.ToUpper())

           {

              case "PNG": img.Save(NewFileName, encoders[4], codecParams); success =
    true; break;

              case "BMP": img.Save(NewFileName, encoders[0], codecParams); success =
    true; break;

              case "JPG": img.Save(NewFileName, encoders[1], codecParams); success =
    true; break;

              case "GIF": img.Save(NewFileName, encoders[2], codecParams); success =
    true; break;

           }

           catch

           {

              MessageBox.Show("Failed to save image to " + NewFileName, "Error",
    MessageBoxButtons.OK, MessageBoxIcon.Error);

              return;

           }

           if (success == true)

              MessageBox.Show("Image file saved to " + NewFileName, "Image Saved",
    MessageBoxButtons.OK, MessageBoxIcon.Information);

    }

    As you can see from the above lengthy block of code, the arguments for our method are the image we are working on, the new file name, and the extension for the new destination file. We then configure our encoder parameters for 100% quality (ergo lossless conversion). We create a success variable for the purpose of error handling.

    Switch is used to delimit each case of conversion depending on the chosen extension. The file saving process uses Image.Save, which saves the image to the specified stream using the specified encoder and encoder parameters. In our case the stream of the image is the object img. The entire switch block is right in the center of a try/catch block. Again, that's what we use to preserve error handling.

    In a nutshell, or perhaps the whole nut in its entirety, this is how we convert images using the .NET environment on C# programming language. I really hope that my instructions and the code fragments were straightforward enough and that you could follow along easily.

    More C# Articles
    More By Barzan "Tony" Antal


       · Thanks for reading the first part of this 2-part series. Don't hesitate to leave...
       · The quality of the result image is poor... with graphics software (gimp, photoshop)...
     

    C# ARTICLES

    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...
    - Polymorphism in C#
    - Inheritance in C#
    - C# Events Explained
    - C# Delegates Explained
    - C# StreamReader and StreamWriter Explained





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway