36. Saving images

The following extension method saves an image with an appropriate file format:

// Save an image in a file with format determined by its extension.
public static void SaveImage(this Image image, string filename)
{
// Check the extension to see what kind of file this should be.
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(
"Unsupported file extension " + extension);
}
}

This method uses the Path.GetExtension method to get the filename's extension. It then uses a switch statement to take different actions depending on the extension.

The switch statement's case blocks call the image's Save method, passing it the filename and a parameter, indicating the correct file format for the extension.

The example solution displays an image, text box, and Save button. When you enter a filename and click the button, the following code saves the image with the filename that you entered:

// Save the image in the appropriate format.
private void saveButton_Click(object sender, EventArgs e)
{
pictureBox1.Image.SaveImage(filenameTextBox.Text);
filenameTextBox.Clear();
filenameTextBox.Focus();
}

This code simply calls the SaveImage extension method to save the image with the desired filename.

If you open the files in MS Paint or some other image editor, you should be able to see the characteristics of the desired formats. For example, PNG files use lossless compression, JPG files use lossy compression, and GIF files use dithering. You can also use File Explorer to see that some formats are compressed more effectively than others.

This method can be a handy part of your image processing toolkit because it prevents you from saving an image in the wrong format. For example, it prevents you from accidentally saving an image in the Smiley.bmp file with the PNG file format.

Download the example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.179.239