BLOG.CSHARPHELPER.COM: Write a method that saves images in an appropriate format depending on the file name's extension in C#
Write a method that saves images in an appropriate format depending on the file name's extension in C#
The Bitmap class provides a Save method that can save an image into a file in many different formats but 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.
This example's SaveBitmapUsingExtension method simply examines a file name's extension and then saves a bitmap using the appropriate format.
// Save the file with the appropriate format. // Throw a NotSupportedException if the file // has an unknown extension. public void SaveBitmapUsingExtension(Bitmap bm, string filename) { string extension = Path.GetExtension(filename); switch (extension.ToLower()) { case ".bmp": bm.Save(filename, ImageFormat.Bmp); break; case ".exif": bm.Save(filename, ImageFormat.Exif); break; case ".gif": bm.Save(filename, ImageFormat.Gif); break; case ".jpg": case ".jpeg": bm.Save(filename, ImageFormat.Jpeg); break; case ".png": bm.Save(filename, ImageFormat.Png); break; case ".tif": case ".tiff": bm.Save(filename, ImageFormat.Tiff); break; default: throw new NotSupportedException( "Unknown file extension " + extension); } }
Comments