Programming Microsoft Windows with C#

Image Class Save Method Ignores Filename Extension

Towards the beginning of the section "More on the Image Class" on page 515, I show three overloads of the Save method. The simplest version has only a filename argument, and I indicate that this particular overload "uses the filename extension to determine the file format," that is, whether to save the Image object as a BMP, JPEG, GIF, PNG, etc.

That statement was true in beta versions of the .NET framework, but it is true no longer. If you have an Image object named img, for example, and you call

the filename extension is ignored. Save will use the original format to determine the format in which to save the Image object. For a metafile, or a bitmap created by the program, Save seems to uses the PNG format by default.

Youíll probably want more control over this process, and in particular, youíll want to avoid creating PNG files with .jpg filename extensions! Use the version of Save that includes an ImageFormat argument:

Two programs in the book are affected by this change in the Save method: ImageIO in Chapter 16, and MetafileConvert in Chapter 23. Both programs use a SaveFileDialog to obtain a filename from the user, and both programs can be fixed in roughly the same way. First, the ImageIO.cs program needs an additional using statement: Thatís for the ImageFormat class. In the MenuFileSaveAsOnClick methods in both ImageIO.cs and MetafileConvert.cs, include an array of ImageFormat objects: Notice that the order of the array elements matches the order of the format descriptions in the Filter string of the SaveFileDialog object. Thatís crucial!

On return from the ShowDialog method of SaveFileDialog, the FilterIndex property will be the one-based index of the file format selected by the user. Use that property (minus 1) to index the ImageFormat array for the second argument to the Save method. In ImageIO.cs, the new Save statement looks like this:

In MetafileConvert.cs, the new Save statement is: This problem is also discussed in Microsoft Knowledge Base Article Q315849. Replacement source code is available from that location.

© Charles Petzold, 2002
This page last updated March, 2002