1

Why does an EMF called blank.emf in Resources end up saved as a bitmap?

private void button1_Click(object sender, EventArgs e)
{
    Metafile emf = null;
    using (var ms = new MemoryStream(Properties.Resources.blank))
    {
        emf = new Metafile(ms);
    }
    emf.Save("C:\\Users\\chrisd\\Documents\\emfbitmap1.emf",
        ImageFormat.Emf);
}

emfbitmap1.emf is a bitmap, not EMF. I am suspecting it is being converted to bitmap upon retrieval from Properties.Resources. It is definitely an EMF on the file system.

Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
  • How does it get form ths MemStream to the resources? How do you establish its type? – bommelding May 22 '18 at 10:31
  • @bommelding The original EMF `blank.emf` was added to the project via Properties > Resources, where it was automatically assigned the name `blank`. `Properties.Resources.blank` accesses this resource. It is originally an EMF so its type should be `Metafile`. – Chris Degnen May 22 '18 at 10:41

1 Answers1

0

The EMF is being converted to a bitmap by the Save operation.

An EMF can be successfully written thanks to this answer, with minor modifications.

using System.Runtime.InteropServices;

including in the class

    [DllImport("gdi32.dll")]
    internal static extern uint GetEnhMetaFileBits(IntPtr hemf,
        uint cbBuffer, byte[] lpbBuffer);

    [DllImport("gdi32.dll")]
    internal static extern bool DeleteEnhMetaFile(IntPtr hemf);

and modifying the code

private void button1_Click(object sender, EventArgs e)
{
    Metafile emf = null;
    using (var ms = new MemoryStream(Properties.Resources.blank))
    {
        emf = new Metafile(ms);
    }

    IntPtr h = emf.GetHenhmetafile();
    uint size = GetEnhMetaFileBits(h, 0, null);
    byte[] data = new byte[size];
    GetEnhMetaFileBits(h, size, data);
    using (FileStream w = File.
        Create("C:\\Users\\chrisd\\Documents\\emfbitmap1.emf"))
    {
        w.Write(data, 0, (int)size);
    }

    DeleteEnhMetaFile(h);
}

Of course, if it is not required to have the EMF in memory it can be written to disc directly. E.g.

private void button1_Click(object sender, EventArgs e)
{
    File.WriteAllBytes("C:\\Users\\chrisd\\Documents\\emfbitmap1.emf",
        Properties.Resources.blank);
}
Chris Degnen
  • 8,443
  • 2
  • 23
  • 40