[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Convert a metafile into a PNG file in C#

[Convert a metafile into a PNG file in C#]

A metafile (WMF file) contains drawing commands that tell a program how to produce an image. This is very useful and allows you to resize the image without producing ugly anti-aliasing effects, but sometimes you may want a raster image so you can manipulate its pixels. This example lets you load WMF files and save them as PNG files.

The program uses the following code to load a WMF file.

// Open a WMF file. private void mnuFileOpen_Click(object sender, EventArgs e) { if (ofdWmfFile.ShowDialog() == DialogResult.OK) { picImage.Image = new Bitmap(ofdWmfFile.FileName); mnuFileSaveAs.Enabled = true; ClientSize = new Size( picImage.Right + picImage.Left, picImage.Bottom + picImage.Left); } }

The code displays a FileOpenDialog to let the user select the metafile. If the user selects a file and clicks Open, the program loads the metafile into a Bitmap and displays it.

The program uses the following code to save the loaded metafile image as a PNG file.

// Save the image as a PNG file. private void mnuFileSaveAs_Click(object sender, EventArgs e) { if (sfdPngFile.ShowDialog() == DialogResult.OK) { Bitmap bm = (Bitmap)picImage.Image; bm.Save(sfdPngFile.FileName, ImageFormat.Png); } }

This code displays a SaveFileDialog to let the user select the file in which to save the image. It then calls the loaded bitmap's Save method passing it the file name and the value ImageFormat.Png to indicate that the image should be saved as a PNG file.

Both WMF and PNG files support transparent pixels. When this program converts a WMF to a PNG file, any transparent pixels are preserved.

In contrast MS Paint doesn't preserve transparent pixels. If you load an image in MS Paint, make some changes, and then save the file, any transparency information is lost.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.