Save copies of the pictures in a directory in a new format (bmp, jpg, png, etc.) in C#

This program lets you enter a directory name and select a graphical file type: bmp, jpg, gif, png, etc. When you click Go, it loads each of the image files in the directory and re-saves the image in the selected file format.

The most interesting work occurs when you click the Go button. The program uses the ExtensionFormat function to determine the image format for the selected extension. For example, the extension .bmp corresponds to the image format ImageFormat.Bmp. The ExtensionFormat function is basically a straightforward switch statement so it isn't shown here.

Next the program gets a DirectoryInfo object for the directory you entered in the TextBox and loops through the directory's files.

For each file, the program gets the file's image format. If the file's format is not null (indicating that it is a graphic format) and is different from the desired new format, the program loads the file into a Bitmap and then saves it in the new format.

// Process the files in the selected directory.
private void btnGo_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
this.Refresh();

// Get the new image format.
string new_ext = cboExtension.Text;
ImageFormat new_format = ExtensionFormat(new_ext);

// Enumerate the files.
DirectoryInfo dir_info = new System.IO.DirectoryInfo(txtDirectory.Text);
foreach (FileInfo file_info in dir_info.GetFiles())
{
try
{
txtProcessing.Text = file_info.Name;
txtProcessing.Refresh();

// See what kind of file this is.
string old_ext = file_info.Extension.ToLower();
ImageFormat old_format = ExtensionFormat(old_ext);

// Only process if the file has a graphic
// extension and we're changing the type
if ((old_format != null) && (old_format != new_format))
{
Bitmap bm = new Bitmap(file_info.FullName);
string new_name = file_info.FullName.Replace(old_ext, new_ext);

bm.Save(new_name, new_format);
}
}
catch (Exception ex)
{
MessageBox.Show("Error processing file '" +
file_info.Name + "'\n" + ex.Message,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
} // foreach file_info

txtProcessing.Clear();
this.Text = "howto_2005_change_picture_types";
this.Cursor = Cursors.Default;
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.