code_junkie

GDI+ / C#: How to save an image as EMF?

Nov 11th, 2011
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. var path = @"c:foo.emf"
  2. var g = CreateGraphics(); // get a graphics object from your form, or wherever
  3. var img = new Metafile(path, g.GetHdc()); // file is created here
  4. var ig = Graphics.FromImage(img);
  5. // call drawing methods on ig, causing writes to the file
  6. ig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();
  7.  
  8. [DllImport("gdi32")] uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer);
  9.  
  10.  
  11. IntPtr h = metafile.GetHenhMetafile();
  12. int size = GetEnhMetaFileBits(h, 0, 0);
  13. byte[] data = new byte[size];
  14. GetEnhMetaFileBits(h, size, data);
  15. using (FileStream w = File.Create("out.emf")) {
  16. w.Write(data, 0, size);
  17. }
  18. // TODO: I don't remember whether the handle needs to be closed, but I guess not.
  19.  
  20. Graphics grfx = CreateGraphics();
  21. MemoryStream ms = new MemoryStream();
  22. IntPtr ipHdc = grfx.GetHdc();
  23.  
  24. Metafile mf = new Metafile(ms, ipHdc);
  25.  
  26. grfx.ReleaseHdc(ipHdc);
  27. grfx.Dispose();
  28. grfx = Graphics.FromImage(mf);
  29.  
  30. grfx.FillEllipse(Brushes.Gray, 0, 0, 100, 100);
  31. grfx.DrawEllipse(Pens.Black, 0, 0, 100, 100);
  32. grfx.DrawArc(new Pen(Color.Red, 10), 20, 20, 60, 60, 30, 120);
  33. grfx.Dispose();
  34.  
  35. mf.Save(@"C:file.emf", ImageFormat.Emf);
  36. mf.Save(@"C:file.png", ImageFormat.Png);
  37.  
  38. <System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetEnhMetaFileBits")> _
  39. Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData As IntPtr) As UInteger
  40. End Function
  41.  
  42. <System.Runtime.InteropServices.DllImportAttribute("gdi32.dll", EntryPoint:="GetEnhMetaFileBits")> _
  43. Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData() As Byte) As UInteger
  44. End Function
  45.  
  46. Dim h As IntPtr = mf.GetHenhmetafile()
  47. CopyEnhMetaFileW(h, FileName)
Add Comment
Please, Sign In to add comment