Question

I am trying to render an .emf file to a bitmap with given size.

Here is my code, I used this answer as base: How do I resize (shrink) an EMF (Metafile) in .Net?

public void SetEmfFromBitmap(string emfPath, Size size)
    {
        if (emfPath.Contains(".emf"))
        {
            using (var source = new Metafile(emfPath))
            using (var target = new Bitmap(size.Width, size.Height))
            using (var g = Graphics.FromImage(target))
            {
                g.DrawImage(source, 0, 0, size.Width, size.Height);
                target.Save("c:\\temp\\Month_Calendar.png", ImageFormat.Png); //this works..
                this.Image = target; //but this doesnt???
            }
        }
        else
        {
            throw new ArgumentException("Invalid path to .emf file: " + emfPath);
        }
    }

The method about belongs to class that is derived from PictureBox. That is why I am setting this.Image (which is a Bitmap). But all I can see is a red cross with white background in my Winforms application.

So what is wrong with the bitmap object?

Was it helpful?

Solution

I found the reason myself: Because of the use of using statement, the target bitmap gets disposed. The answer is to use this.Image = (Bitmap)target.Clone(); instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top