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.
Next: Taking a Break >>
More C# Articles
More By Barzan "Tony" Antal