0

I new to WPF and I am trying to render simple line to bitmap and save it to the PNG file. But I got empty Bitmap instead.

What I am doing wrong?

void RenderLineToFile()
{
    var bitmap = RenderBitMap();
    SaveImageToFile("image.png", bitmap);
}


RenderTargetBitmap RenderBitMap()
{
     int bitmapWidth = 100;
     int bitmapHeight = 100;
     double dpiX = 72;
     double dpiY = 72;         

     RenderTargetBitmap bm = new RenderTargetBitmap(bitmapWidth, bitmapHeight, dpiX, dpiY, PixelFormats.Pbgra32);

     DrawingVisual drawing_visual = new DrawingVisual();
     using (DrawingContext drawing_context = drawing_visual.RenderOpen())
     {
         Pen penBlack = new Pen(Brushes.Black, 1.0);

         drawing_context.DrawLine(penBlack, new Point(0, 0), new Point(100, 100));

         bm.Render(drawing_visual);
     }            
     return bm;
}

public static void SaveImageToFile(string filePath, BitmapSource image)
{
     using (var fileStream = new FileStream(filePath, FileMode.Create))
     {
         BitmapEncoder encoder = new PngBitmapEncoder();
         encoder.Frames.Add(BitmapFrame.Create(image));
         encoder.Save(fileStream);
     }
}
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
  • 2
    Maybe this [According to MSDN, "A DrawingContext must be closed before its content can be rendered"](http://stackoverflow.com/a/869767/815938)? Try taking `bm.Render(drawing_visual); ` outside of the using clause. – kennyzx May 10 '17 at 06:54
  • Yes, its working! – Tomas Kubes May 10 '17 at 07:07

1 Answers1

1

According to MSDN,

A DrawingContext must be closed before its content can be rendered...

Try taking bm.Render(drawing_visual); outside of the using clause.

kennyzx
  • 12,845
  • 6
  • 39
  • 83