[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Save images with an appropriate format depending on the file name's extension in C#

save images with an appropriate format

The Image class (and thus the Bitmap class that inherits from Image) provides a Save method that can save an image into a file in many different formats. Unfortunately that method doesn't look at the file name's extension to decide which format to use. For example, you could save an image in JPEG format in a file with a .bmp extension. That could be confusing and might even mess up some applications that tried to read the file as a bitmap.

This example uses the following SaveImage method. It examines a file name's extension and then saves the image using the appropriate format.

// Save the file with the appropriate format. public void SaveImage(Image image, string filename) { string extension = Path.GetExtension(filename); switch (extension.ToLower()) { case ".bmp": image.Save(filename, ImageFormat.Bmp); break; case ".exif": image.Save(filename, ImageFormat.Exif); break; case ".gif": image.Save(filename, ImageFormat.Gif); break; case ".jpg": case ".jpeg": image.Save(filename, ImageFormat.Jpeg); break; case ".png": image.Save(filename, ImageFormat.Png); break; case ".tif": case ".tiff": image.Save(filename, ImageFormat.Tiff); break; default: throw new NotSupportedException( "Unknown file extension " + extension); } }

This method simply examines the file name's extension and then saves the image using the appropriate format.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.