GDI+ / C#: How to save an image as EMF?
If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (http://msdn.microsoft.com/en-us/library/ktx83wah.aspx)
Is there another way to save the image to an EMF/WMF? Are there any encoders available?
Image
is an abstract class: what you want to do depends on whether you are dealing with a Metafile
or a Bitmap
.
Creating an image with GDI+ and saving it as an EMF is simple with Metafile
. Per Mike's post:
var path = @"c:\foo.emf"
var g = CreateGraphics(); // get a graphics object from your form, or wherever
var img = new Metafile(path, g.GetHdc()); // file is created here
var ig = Graphics.FromImage(img);
// call drawing methods on ig, causing writes to the file
ig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();
This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands.
You can save a Bitmap
to an EMF file by using the above method and calling ig.DrawImage(your_bitmap)
, but be aware that this does not magically covert your raster data into a vector image.
If I remember correctly, it can be done with a combination of the Metafile.GetHenhmetafile(), the API GetEnhMetaFileBits() and Stream.Write(), something like
[DllImport("gdi32")] static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer);
IntPtr h = metafile.GetHenhMetafile();
int size = GetEnhMetaFileBits(h, 0, null);
byte[] data = new byte[size];
GetEnhMetaFileBits(h, size, data);
using (FileStream w = File.Create("out.emf")) {
w.Write(data, 0, size);
}
// TODO: I don't remember whether the handle needs to be closed, but I guess not.
I think this is how I solved the problem when I had it.
A metafile is a file which records a sequence of GDI operations. It is scalable because the original sequence of operations that generated the picture are captured, and therefore the co-ordinates that were recorded can be scaled.
I think, in .NET, that you should create a Metafile
object, create a Graphics
object using Graphics.FromImage
, then perform your drawing steps. The file is automatically updated as you draw on it. You can find a small sample in the documentation for Graphics.AddMetafileComment.
If you really want to store a bitmap in a metafile, use these steps then use Graphics.DrawImage
to paint the bitmap. However, when it is scaled it will be stretched using StretchBlt
.