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

save images with an appropriate format

This example shows how to 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 Example


This entry was posted in files, graphics. Bookmark the permalink.

4 Responses to Save images with an appropriate format depending on the file name’s extension in C#

  1. Pingback: Resize images and save the results in C# |

  2. Pingback: Resize pictures in a directory in C# |

  3. Pingback: Save an image of the computer's screen in a file in C# -

  4. Pingback: Crop a picture in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *