Title: Save images with an appropriate format depending on the file name's extension in C#
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.
|