10.17 Converting Image File Formats

 <  Day Day Up  >  

You want to convert an image from one file format to a different file format.


Technique

To convert a file format, you need to save it to the file system, specifying which format you want to save the image to. Call the Save method from an Image instance, passing a filename to save the image to and a value from the ImageFormat enumerated data type:

 
 private void menuSave_Click(object sender, System.EventArgs e) {     if( image == null )         return;     if( saveFileDialog1.ShowDialog(this) == DialogResult.OK )     {         ImageFormat format = ImageFormat.Bmp;         if( saveFileDialog1.FileName.EndsWith("bmp"))         {             format = ImageFormat.Bmp;         }         else if( saveFileDialog1.FileName.EndsWith("gif"))         {             format = ImageFormat.Gif;         }         else if( saveFileDialog1.FileName.EndsWith("jpg"))         {             format = ImageFormat.Jpeg;         }         else if( saveFileDialog1.FileName.EndsWith("png"))         {             format = ImageFormat.Png;         }         // other file formats ...         image.Save( saveFileDialog1.FileName, format );         image = Image.FromFile( saveFileDialog1.FileName );         this.Text = "Image Test - " + saveFileDialog1.FileName;     } } 

Comments

The code allows a user to save an image in one of four different file formats, but GDI+ allows you to save an image using 10 different formats. The code to support all different file formats therefore appears redundant for illustration purposes. It makes sense for the Save method to simply determine the file format to save the image to based on the file extension, as shown in the code earlier, and at one point in the development of the Image class, this was the case. For unknown reasons, however, this design was changed in favor of the ImageFormat enumerated data type.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net