Monday, February 25, 2008

Creating a metafile in .NET

Metafiles are a way to save scalable vectory graphics. This blog creates a simple image containing a diagonal line. It also shows the proper way to save the metafile, as the class method saves it as a png file.

MSDN article on MetaFiles: http://msdn2.microsoft.com/en-us/library/ms536391.aspx



using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;




MemoryStream metafileStream = new MemoryStream();


Graphics offScreenDC = Graphics.FromHwndInternal(IntPtr.Zero);


IntPtr myImagePointer = offScreenDC.GetHdc();


Metafile meta =
//new Metafile(myImagePointer, EmfType.EmfOnly); //unable to do memoryStreamSave
new Metafile(metafileStream, myImagePointer, EmfType.EmfOnly); //able to do memoryStreamSave


Graphics aGraphic = Graphics.FromImage(meta);


aGraphic.DrawLine(new Pen(Brushes.Black), new Point(0, 0), new Point(29, 29));


aGraphic.Dispose(); //Dispose must be called to flush the drawing instructions.


offScreenDC.ReleaseHdc();
meta.Save(@"c:\metaSave.wmf"); //saves as a png file.


FileStream aWrite = new FileStream(@"c:\StreamSave.wmf",FileMode.Create); //saves as a wmf file


metafileStream.WriteTo(aWrite);

2 comments:

Anonymous said...

You are my hero today.

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.