Tomas Kubes
Tomas Kubes

Reputation: 25098

How to render line to PNG bitmap i WPF?

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);
     }
}

Upvotes: 0

Views: 139

Answers (1)

kennyzx
kennyzx

Reputation: 12993

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.

Upvotes: 1

Related Questions