Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Windows Metafile?

I need to display a Windows Metafile (EMF) using WPF, how can I do?

Edit:

I'd to keep the image vector-based.

like image 819
gliderkite Avatar asked Apr 13 '12 19:04

gliderkite


1 Answers

Here is a utility function that loads an EMF file and converts it into a WPF BitmapSource:

public static class Emfutilities
{
        public static BitmapSource ToBitmapSource(string path)
        {
            using (System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(path))
            using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height))
            {
                bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution);
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
                {
                    g.DrawImage(emf, 0, 0);
                    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                }
            }
        }
}

You simply use it like this:

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            // img is of Image type for example
            img.Source = Emfutilities.ToBitmapSource("SampleMetafile.emf");
        }
    }

}

The drawback is you will need to reference System.Drawing.dll (GDI+) into your WPF application, but that should not be a big issue.

like image 101
Simon Mourier Avatar answered Oct 26 '22 03:10

Simon Mourier