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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in drawing, files, graphics, image processing and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Convert a metafile into a PNG file in C#

  1. lindexi says:

    I found it cant use in wpf for some file cant show and I try to use [How to convert emf to ImageSource in WPF? – CodeProject]( ) that I can show it.

  2. RodStephens says:

    One of the biggest failures in WPF (IMHO) is its support for image processing. It doesn’t provide many tools for manipulating images at a pixel level.

    I would try adding a reference to Windows Forms and using the methods described here. Then you can move the image in and out of the WPF code.

Comments are closed.